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

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



CWorkerServiceInfoUpdater::CWorkerServiceInfoUpdater()
{

}

CWorkerServiceInfoUpdater::~CWorkerServiceInfoUpdater()
{

}

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

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

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

		m_launched = false;
	}

	return m_pid;
}


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

	// account shared memory 생성
	int nMaxAccount = CDeamonConfig::GetInstance()->GetMaxAccount();
	int nAccountMemSize = (sizeof(struct account) * nMaxAccount);

	if (m_shmemAccount.Create("/tmp/opendav.shared.account.shm", nAccountMemSize, p) == false)
	{
		LOG(LERR, "Account shared memory create failed.");
		exit(EXIT_FAILURE);
	}

	// anony shared memory 생성
	int nMaxAnony = CDeamonConfig::GetInstance()->GetMaxAnonyMous();
	int nAnonyMemSize = (sizeof(struct anonymous) * nMaxAnony);
	
	if (m_shmemAnoymous.Create("/tmp/opendav.shared.anony.shm", nAnonyMemSize, p) == false)
	{
		LOG(LERR, "Anony shared memory create failed.");
		exit(EXIT_FAILURE);
	}

	if( m_objAccount.ThreadInit(sighandle, &m_shmemAccount ) == false )
	{
		LOG(LERR, "CAccountUpdate Thread create failed.");
		exit(EXIT_FAILURE);
	}

	if( m_objAnony.ThreadInit(sighandle, &m_shmemAnoymous ) == false )
	{
		LOG(LERR, "CAnonyUpdate Thread create failed.");
		exit(EXIT_FAILURE);
	}

	SetThreadSignal(SIGINT);
	SetThreadSignal(SIGTERM);
	
	if( m_objAccount.Start() == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "CAccountUpdate Thread start failed.");
		exit(EXIT_FAILURE);
	}
	if( m_objAnony.Start() == false )
	{
		UnSetThreadSignal(SIGINT);
		UnSetThreadSignal(SIGTERM);
		LOG(LERR, "CAnony Thread start failed.");
		exit(EXIT_FAILURE);
	}
	UnSetThreadSignal(SIGINT);
	UnSetThreadSignal(SIGTERM);
}
