/*++

Copyright (c) 1999  Digi International

Module Name:

    util.c

Abstract:

    This function contains the DLL entry point to laod and 
	unload Performance Monitor 

Author:

    Jeff Romatoski

Revision History:

--*/
#include <windows.h>
#include <direct.h>
#include <stdlib.h>
#include <stdio.h>

enum
{
	ARG_CMD = 0,
	ARG_COUNT
} ARGS;

#define INFENTRYPOINT_FAILURE 0
#define INFENTRYPOINT_SUCCESS 1

/////////////////////////////////////////////////////////////////////////////
// The entry point into this DLL used by the INF
extern BOOL PASCAL PerfMonUtilities(DWORD cArgs, LPSTR apszArgs[], LPSTR *pszTextOut)
{

	static char szErrorMsg[256];

	char const * const pszSuccess			= "Success";
	char const * const pszWrongNumberofArgs = "Wrong Number of Arguments Input = %d, Expected = %d";
	char const * const pszProcessError		= "Process Error: LastError = %d";

	DWORD dwInfEntryPointStatus = INFENTRYPOINT_FAILURE;
	sprintf(szErrorMsg,pszSuccess);
	*pszTextOut = szErrorMsg;

	if (cArgs != ARG_COUNT)
	{
	   sprintf(szErrorMsg,pszWrongNumberofArgs,ARG_COUNT,cArgs);
	}
	else
	{

		 // Run the process (lodctrs or unlodctr)

		STARTUPINFO			si;
		PROCESS_INFORMATION	pi;
		TCHAR				szSystemDir[MAX_PATH];
		TCHAR				szOldDir[MAX_PATH];

		// The current working directory must point to the system directory
		getcwd(szOldDir,MAX_PATH);
		GetSystemDirectory(szSystemDir, MAX_PATH * sizeof(*szSystemDir));
		chdir(szSystemDir);
#ifdef _DEBUG
		// Print the Arguments in Debug Mode
		{
			char szDebugString[512];
			sprintf(szDebugString,"CWD  = %s\n",szSystemDir);
			OutputDebugString(szDebugString);
			sprintf(szDebugString,"ARG1 = %s\n",apszArgs[ARG_CMD]);
			OutputDebugString(szDebugString);
		}
#endif //_DEBUG

		// Execute the command with a call to the CreateProcess API call.
		memset(&si,0,sizeof(STARTUPINFO));
		si.cb			= sizeof(STARTUPINFO);
		if (!CreateProcess(NULL,
						   apszArgs[ARG_CMD],
						   NULL,
						   NULL,
						   FALSE,
						   DETACHED_PROCESS,
						   NULL,
						   NULL,
						   &si,
						   &pi))
		{			
			// Error
			sprintf(szErrorMsg,pszProcessError,GetLastError());
		} 
		else
		{
			/* wait for completion. */
			WaitForSingleObject(pi.hProcess, INFINITE);

			/* close process and thread handles */
			CloseHandle(pi.hThread);
			CloseHandle(pi.hProcess);
			dwInfEntryPointStatus = INFENTRYPOINT_SUCCESS;
		}

		// Set the Old Working Directory
		chdir(szOldDir);

	}

	return dwInfEntryPointStatus;

}