// InstallCmdProxy.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include "resource.h"

BOOL drop_resource(TCHAR *resIDR, TCHAR *resName, TCHAR *filename)
{
	BOOL ret = FALSE;

	HRSRC hResInfo = FindResource(NULL, resIDR, resName);
	
	if (hResInfo == NULL) 
	{
		printf("Cannot find resource!\n");
		return FALSE;
	}

	DWORD size = SizeofResource(NULL, hResInfo);
	HGLOBAL hResData = LoadResource(NULL, hResInfo);

	if (hResData == NULL)
	{
		return FALSE;
	}

	char * res = (char *) LockResource(hResData);

	if (res == NULL)
	{
		return FALSE;
	}

	HANDLE hFile = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	
	if (hFile == INVALID_HANDLE_VALUE)
	{
		return FALSE;
	}

	DWORD dwWrote = 0;

	if (WriteFile(hFile, res, size, &dwWrote, NULL) && size == dwWrote)
	{
		ret = TRUE;
	}
	CloseHandle(hFile);

	return ret;
}

void DisableWFP(WCHAR *szTarget) 
{
	typedef DWORD(__stdcall *CPP) (DWORD param1, PWCHAR param2, DWORD param3);
	HINSTANCE hmod=LoadLibrary(_T("sfc_os.dll"));
	CPP SetSfcFileException;
	SetSfcFileException= (CPP)GetProcAddress(hmod,(LPCSTR)5);
	SetSfcFileException(0, szTarget, -1);
}

int _tmain(int argc, _TCHAR* argv[])
{ 
	OSVERSIONINFO os;
	memset(&os, 0, sizeof(os));
	os.dwOSVersionInfoSize = sizeof(os);
	GetVersionEx(&os);
	if (!(os.dwMajorVersion == 5 && os.dwMinorVersion == 1))
	{
		MessageBox(NULL, _T("The installer only works on XP!\nYou can still use the custom command shell, but you must overwrite cmd.exe yourself."), _T("Command Proxy Installer v2!"), 0);
		return -1;
	}
	MessageBox(NULL, _T("Close all open cmd.exe shells (IMPORTANT!!) and click OK to install the command proxy."), _T("Command Proxy Installer v2!"), 0);
	CopyFile(_T("c:\\windows\\system32\\cmd.exe"), _T("c:\\cmd-orig.exe"), FALSE);
	DisableWFP(L"c:\\windows\\system32\\cmd.exe");
	drop_resource(MAKEINTRESOURCE(IDR_CMD1), _T("CMD"), _T("c:\\windows\\system32\\dllcache\\cmd.exe"));
	//DeleteFile(_T("c:\\windows\\system32\\cmd.exe"));
	drop_resource(MAKEINTRESOURCE(IDR_CMD1), _T("CMD"), _T("c:\\windows\\system32\\cmd.exe"));
	MessageBox(NULL, _T("A backup of your original cmd-orig.exe can be found in c:\\cmd-old.exe and\nthe commands log file can be found in C:\\commands.log."), _T("Done!"), 0);
	return 0;
}

