#include "WorkerFhsInfoUpdater.h"
#include <sstream>

#include "Logger.h"
#include "DaemonConfigs.h"



CWorkerFhsInfoUpdater::CWorkerFhsInfoUpdater()
{

}

CWorkerFhsInfoUpdater::~CWorkerFhsInfoUpdater()
{

}

pid_t CWorkerFhsInfoUpdater::Launcher(const sig_atomic_t *sighandle)
{
	Fork();

	if (m_pid == 0)
	{
	
		while (*sighandle == 0)
		{
			// work
			set_ps_display("Worker [Fhs Info Updater]", false);
			do_work(sighandle);
			
			// signal 받은 경우 wait 불필요
			if(*sighandle == 0)
			{
				pause();
			}
		}

		// httpd 구동 여부에 따라 Detache or Destroy를 결정함
		if(IsProcessRun("httpd") == true)
		{
			m_objFhsStat.SetSelfDead();
			m_shmemFhsStat.Detach();
			m_shmemFhsCount.Detach();
			LOG(LDBG, "m_shmemFhsStat.Detach()");
		}
		else
		{
			m_shmemFhsStat.Destroy();
			m_shmemFhsCount.Destroy();
			LOG(LDBG, "m_shmemFhsStat.Destroy()");
		}

		m_launched = false;
	}

	return m_pid;
}


void CWorkerFhsInfoUpdater::do_work(const sig_atomic_t *sighandle)
{
	apr_pool_t *p;
	apr_pool_create(&p, NULL);

	// fhsstat shared memory 생성
	int nMaxFhs = CDeamonConfig::GetInstance()->GetMaxFhs();
	int nMaxFhsMemSize = (sizeof(struct fhs_stat) * nMaxFhs);

	if (m_shmemFhsStat.Create("/tmp/opendav.shared.fhsstat.shm", nMaxFhsMemSize , p) == false)
	{
		LOG(LERR, "FHS stat shared memory create failed.");
		exit(EXIT_FAILURE);
	}
	
	if (m_shmemFhsCount.Create("/tmp/opendav.shared.fhscount.shm", 4 , p) == false)
	{
		LOG(LERR, "FHS stat shared memory create failed.");
		exit(EXIT_FAILURE);
	}


	if( m_objFhsStat.ThreadInit(sighandle, &m_shmemFhsStat, &m_shmemFhsCount ) == false )
	{
		LOG(LERR, "Fhs stat update thread create failed.");
		exit(EXIT_FAILURE);
	}

	SetThreadSignal(SIGINT);
	SetThreadSignal(SIGTERM);
	
	if( m_objFhsStat.Start() == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "Fhs stat update thread create failed.");
		exit(EXIT_FAILURE);
	}
	UnSetThreadSignal(SIGINT);
	UnSetThreadSignal(SIGTERM);
}
