#include "StdAfx.h"
#include "SystemServiceControl.h"


/*!
	サービスは存在するか？
*/
int CSystemServiceControl::ServiceInstalled()
{
	SC_HANDLE	scm = ::OpenSCManager(NULL,SERVICES_ACTIVE_DATABASE,SC_MANAGER_CONNECT);
	if(scm == NULL)
		return(FALSE);

	SC_HANDLE	service = ::OpenService(scm, SERVICE_NAME, SERVICE_START | SERVICE_STOP);
	if(service == NULL)
	{
		CloseServiceHandle(scm);
		return(FALSE);	//	無いっぽい
	}

	CloseServiceHandle(service);
	CloseServiceHandle(scm);
	return(TRUE);
}

/*!
	サービス開始
*/
int CSystemServiceControl::StartSystemService()
{
	SC_HANDLE	scm = ::OpenSCManager(NULL,SERVICES_ACTIVE_DATABASE,SC_MANAGER_CONNECT);
	if(scm == NULL)
		return(-1);

	SC_HANDLE	service = ::OpenService(scm, SERVICE_NAME, SERVICE_START | SERVICE_STOP | SERVICE_QUERY_STATUS);
	if(service == NULL)
	{
		CloseServiceHandle(scm);
		return(-1);	//	無いっぽい
	}

	//	開始
	int ret = 0;
	SERVICE_STATUS stat;
	::QueryServiceStatus(service,&stat);
	if(stat.dwCurrentState == SERVICE_STOPPED)
	{
		if(!::StartService(service, 0, NULL))
			ret = -1;
		WaitStartService(service);
	}
	else if(stat.dwCurrentState == SERVICE_PAUSED)
	{
		if(!::ControlService(service, SERVICE_CONTROL_CONTINUE, &stat))
			ret = -1;
		WaitStartService(service);
	}

	CloseServiceHandle(service);
	CloseServiceHandle(scm);
	return(ret);
}

//!	サービス開始まで待つ
int CSystemServiceControl::WaitStartService(SC_HANDLE	service)
{
	//	起動まで待つ
	for(int i=0;i<50;i++)
	{
		SERVICE_STATUS stat;
		::QueryServiceStatus(service,&stat);
		if(stat.dwCurrentState != SERVICE_START_PENDING && stat.dwCurrentState != SERVICE_CONTINUE_PENDING)
			return(0);
		Sleep(100);
	}
	return(-1);
}
