/*
 * Ce programme gere le service "Mcx" (Il peut etre facilement adapte a
 * n'importe quel autre service).
 * Si le service "Mcx" est en cours d'execution, il est arrete.
 * Si le service "Mcx" est arrete, il est redemarre.
 *
 * Copyright(c) by Acksys, 1999
 */
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

#define MCX_SERVICE	"Mcx"

char * StateString(int state);

main()
{
	SC_HANDLE scm;
	SC_HANDLE svc;
	SERVICE_STATUS status;

	scm = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
	if(scm == NULL){
		printf("OpenSCManager: error %d\n", GetLastError());
		exit(1);
	}
	svc = OpenService(scm, MCX_SERVICE, SERVICE_ALL_ACCESS);
	if(svc == NULL){
		printf("OpenService: error %d\n", GetLastError());
		exit(1);
	}
	if( !QueryServiceStatus(svc,&status) ){
		printf("QueryServiceStatus: error %d\n", GetLastError());
		exit(1);
	}
	printf("Previous state: %s\n",StateString(status.dwCurrentState));
	if(status.dwServiceType != SERVICE_KERNEL_DRIVER){
		printf("%s: Not a kernel driver.\n",MCX_SERVICE);
		exit(1);
	}

	if(status.dwControlsAccepted & SERVICE_ACCEPT_STOP)
		printf("%s accepte la commande STOP\n", MCX_SERVICE);
	switch(status.dwCurrentState){
	case SERVICE_STOPPED:
		StartService(svc,0,NULL);
		if( !QueryServiceStatus(svc,&status) ){
			printf("QueryServiceStatus: error %d\n",GetLastError());
			exit(1);
		}
		printf("New state: %s\n",StateString(status.dwCurrentState));
		break;
	case SERVICE_RUNNING:
		ControlService(svc,SERVICE_CONTROL_STOP,&status);
		printf("New state: %s\n",StateString(status.dwCurrentState));
		break;
	default:
		printf("No action taken\n");
	}
}

char *
StateString(int state)
{
	char *str;

	switch(state){
	case SERVICE_STOPPED:		str = "The service is not running.";
					break;
	case SERVICE_START_PENDING:	str = "The service is starting.";
					break;
	case SERVICE_STOP_PENDING:	str = "The service is stopping.";
					break;
	case SERVICE_RUNNING:		str = "The service is running.";
					break;
	case SERVICE_CONTINUE_PENDING:	str = "Service continue is pending.";
					break;
	case SERVICE_PAUSE_PENDING:	str = "Service pause is pending.";
					break;
	case SERVICE_PAUSED:		str = "The service is paused.";
					break;
	default:			str = "Unknown service state.";
					break;
	}
	return str;
}
