// Perforce 2005.1 Loader.cpp : Defines the entry point for the console application.
//

#define _CRT_SECURE_NO_DEPRECATE

#include "stdafx.h"
#include <windows.h>
#include <process.h>

int _tmain(int argc, _TCHAR* argv[])
{
	if(argc != 2)
	{
		printf("Usage: p4sloader [perforce path]\n");
	}
	else
	{
		// Local variables
		int change = -1;
		char counterFilePath[1024];
		char p4dPath[1024];
		char p4Path[1024];
		char loginBatPath[1024];

		sprintf(counterFilePath, "%s\\db.counters", argv[1]);
		sprintf(p4dPath, "%s\\p4d.exe", argv[1]);
		sprintf(p4Path, "%s\\p4.exe", argv[1]);
		GetCurrentDirectory(1024, loginBatPath);
		strcat(loginBatPath, "p4sloader.bat");

		// Read change counter from Perforce
		FILE *counterFile = fopen(counterFilePath, "rb+");

		if(counterFile)
		{
			// Read entire counter file into memory
			fseek(counterFile, 0, SEEK_END);
			long counterFileSize = ftell(counterFile);

			char *dataBuffer = new char [counterFileSize];
			fseek(counterFile, 0, SEEK_SET);
			fread(dataBuffer, counterFileSize, 1, counterFile);

			// Parse counter file and look for the change string
			const char *changeString = "change";
			int changeStringLength = static_cast<int>(strlen(changeString));
			for(int i = 0; i < counterFileSize; ++i)
			{
				if(memcmp(changeString, &dataBuffer[i], changeStringLength) == 0)
				{
					int changeLocation = i + changeStringLength + 2;

					// Read change value
					fseek(counterFile, changeLocation, SEEK_SET);
					fread(&change, sizeof(int), 1, counterFile);

					// Proceed only if a valid change number was retrieved
					if(change >= 0)
					{
						printf("Change Number: %d\n", change);

						// Reset change value
						int dummyChangeValue = 1;
						fseek(counterFile, changeLocation, SEEK_SET);
						fwrite(&dummyChangeValue, sizeof(int), 1, counterFile);

						fclose(counterFile);

						// Spawn the p4d service
						_spawnl(_P_DETACH, p4dPath, "p4d.exe", NULL);

						// Pause for a bit while the service starts
						Sleep(10000);

						// Force login first
						_spawnl(_P_WAIT, loginBatPath, "p4sloader.bat", NULL);

						// Pause for a bit while the login registers
						Sleep(5000);

						// Reset counter
						char changeString[200];
						sprintf(changeString, "%d", change);
						_spawnl(_P_WAIT, p4Path, "p4.exe", "counter", "-f", "change", changeString, NULL);

						return 0;
					}

					break;
				}
			}

			fclose(counterFile);
		}
		else
		{
			printf("[ERROR] db.counters path is invalid.\n");
		}
	}

	return 0;
}

