#define STRICT
#include <Windows.h>
#include <process.h>
#include <tchar.h>
#include <stdio.h>

#ifdef PLATFORM_SDK
#include <strsafe.h>
#endif

// Helper function for displaying error codes
void ErrorExit(char* lpszFunction) 
{ 
  // Retrieve the system error message for the last-error code
  
  char* lpMsgBuf = NULL;
  char* lpDisplayBuf = NULL;
  DWORD dw = GetLastError(); 
  
  FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER | 
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		dw,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(char*) &lpMsgBuf,
		0, NULL );
  
  // Display the error message and exit the process
  //lpDisplayBuf = new char[(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)];
  lpDisplayBuf = (char*)LocalAlloc(LMEM_ZEROINIT, 
				   (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); 
  
#ifdef PLATFORM_SDK
  StringCchPrintf((LPTSTR)lpDisplayBuf, 
		  LocalSize(lpDisplayBuf) / sizeof(TCHAR),
		  TEXT("%s Failed with error %d: %s"), 
		  lpszFunction, dw, lpMsgBuf); 
#else
  _stprintf(lpDisplayBuf, __TEXT("%s\nFailed with error %d: %s"), lpszFunction, dw, lpMsgBuf);
#endif
  
  MessageBox(NULL, lpDisplayBuf, TEXT("Error"), MB_OK); 
  
  fprintf(stderr,"Cleaning up\n");    

  LocalFree(lpMsgBuf);
  LocalFree(lpDisplayBuf);
  ExitProcess(dw); 
}

// If using the following non-GUI method definition, need to launch
// the StartHttpd.exe program with: cmd /c
// (which would make it a detached process - with its own console)
// int _tmain( int argc, TCHAR *argv[] )
 
extern "C" int WINAPI _tWinMain(HINSTANCE hinst, HINSTANCE hinstExePrev, 
                                 LPTSTR pszCmdLine, int nShowCmd) 
{
  if(__argc < 2 ||__argc > 3) {
    MessageBox(NULL, __TEXT("Usage: stophttpd.exe <event-name> [SILENT]"),
	       TEXT("Error"), MB_OK);
    return(-1);
  }
  
  // open (get) the existing named event object that the StartHttpd.exe is listening for.
  // The event object's name is what is given in the command line
  HANDLE g_heventTerminateProcessGroup = OpenEvent(EVENT_ALL_ACCESS,TRUE, __argv[1]);
  
  // send the termination event
  if (SetEvent(g_heventTerminateProcessGroup)==0) {
    // no popup if in SILENT mode (3rd arg == silent or SILENT)
    if(__argc != 3 || _stricmp(__argv[2], "SILENT\0") != 0) {
      // do error popup ExitError
      
      ErrorExit(TEXT("Failed to send termination event: httpd.exe needs to be terminated manually."));
      fprintf(stderr, "Failed to send termination event: httpd.exe needs to be terminated manually.\n");
    }
  }
  
  //Sleep(3000);
  
  return(0);
}

