<?php
# Check-In Module for DMMT System

	error_reporting(E_ALL);
	ini_set('display_errors', 1);

	Include('inc/IncludeLib.php');

	$Settings['Debug'] = True;
	$Settings['DebugLevel'] = 5;

	GetValueFromURL('Debug'); //-> Get  from URL	
		If ($Settings['Debug'] != "") { $Settings['Debug'] = $Settings['Debug']; }

	If ($Settings['Debug']) {
		$Settings['hDebugLogFile'] = FOpen("DebugLog.txt", "w"); //-> Open NEW File for output
		LogEvent(1, "Okay, Starting things up....", True, False);
	}

#> Checkin Settings
	$Settings['AuthTokenKey'] = "12365548844523357";
	$Settings['NodesConfigPath'] = "../Config";
	

#> Database Settings
	$Settings['DatabaseCheckin'] = True;
	$Settings['DB_Host'] = "MySQL";
	$Settings['DB_User'] = "dm_dm";
	$Settings['DB_Password'] = "stupidputty";
	$Settings['DB_Name'] = "DesktopMasters.com";
	$Settings['DB_NodesTable'] = "dmss_nodes";
	$Settings['DB_Port'] = 3306;

#------------------------------------------------------------------------
	$aPostData = GetJSondata("");

#> Read in Post Data
	$sComputerName = $aPostData['ComputerName'];
	$sCheckInTime = $aPostData['CheckInTime'];
	$iServerStatusNo = $aPostData['ServerStatusNo'];
	$bPrimaryGroupSwitch = $aPostData['PrimaryGroupSwitch'];
	$sOldPrimaryGroup = $aPostData['OldPrimaryGroup'];
	$sPrimaryGroup = $aPostData['PrimaryGroup'];


	If ($bPrimaryGroupSwitch == "True") {
		Print "PrimaryGroupSwitch: ".$bPrimaryGroupSwitch."\n";
		MoveConfigFile($sComputerName, $sOldPrimaryGroup, $sPrimaryGroup);
	}

	CheckIn($sComputerName, $sPrimaryGroup, $iServerStatusNo, $sCheckInTime);

	If ($Settings['Debug']) {
		LogEvent(1, "Process Complete: Terminating Script Naturally...");
		LogEvent(1, "Bye!! Thanks for all the Fish!", False, False);
		FClose($Settings['hDebugLogFile']);
	}
	
	Exit;

#==========================================================================================================
Function MoveConfigFile($sComputerName, $sOldPrimaryGroup, $sPrimaryGroup) {
	Global $Settings;

	$LocalDebugLevel = 1;
	LogEvent($LocalDebugLevel, "In MoveConfigFile()");

	$Source = "";
	$Destination = "";
	
	If (File_Exists($Settings['NodesConfigPath'] . "/" . $sOldPrimaryGroup . "/" . $sComputerName . ".ini")) { //-> Locating Sorce File
		$Source = $Settings['NodesConfigPath'] . "/" . $sOldPrimaryGroup . "/" . $sComputerName . ".ini";
		LogEvent($LocalDebugLevel+1, "Found Source Location: ".$Source);
	} ElseIf (StrPos($sComputerName, $sOldPrimaryGroup) !== False ){
		If (StrPos($sComputerName, "-") !== False ){
			LogEvent($LocalDebugLevel+1, "Computer Name has a hyphen, using left side as gorup name..");
			If (File_Exists($Settings['NodesConfigPath'] . "/" . Str_iReplace("-", "/", $sComputerName) . ".ini")) {
				$Source = $Settings['NodesConfigPath'] . "/" . Str_iReplace("-", "/", $sComputerName) . ".ini";
				LogEvent($LocalDebugLevel+1, "Found Source Location: ".$Source);
			} Else {
				LogEvent(1, "ERROR: Cound not find source location", False, False);
			}
		}
	}
	
	If (!Empty($Source)) {
		If (!Is_Dir($Settings['NodesConfigPath']."/".$sPrimaryGroup)) {
			MkDir($Settings['NodesConfigPath']."/".$sPrimaryGroup);
		}
		If ( $sPrimaryGroup."-" == SubStr($sComputerName, 0, StrLen($sPrimaryGroup."-")) ) {
			$Destination = $Settings['NodesConfigPath'] . "/" . Str_iReplace("-", "/", $sComputerName) . ".ini";
		} Else {
			$Destination = $Settings['NodesConfigPath'] . "/" . $sPrimaryGroup . "/" . $sComputerName . ".ini";
		}
		LogEvent($LocalDebugLevel+1, "Set Destination to: ".$Destination);

		If (!Empty($Destination)) {
			LogEvent($LocalDebugLevel+1, "Moving Config File from ".$Source." to ".$Destination);
			Rename($Source, $Destination);
		}
	}
	
	If (!File_Exists($Settings['NodesConfigPath']."/".$sOldPrimaryGroup."/*.*")) { //-> If old group folder is empty it removes it (Housekeeping).
		LogEvent($LocalDebugLevel+1, "Removing Old Group Folder: ".$Settings['NodesConfigPath']."/".$sOldPrimaryGroup."/");
		RmDir($Settings['NodesConfigPath']."/".$sOldPrimaryGroup."/");
	}
	
	Return;
}
#----------------------------------------------------------------------------------------------------------
Function CheckIn($sComputerName, $sPrimaryGroup, $iServerStatusNo, $sCheckInTime) {
	Global $Settings;

	$LocalDebugLevel = 1;
	LogEvent($LocalDebugLevel, "In CheckIn()");

	LogEvent($LocalDebugLevel+1, "Save Folder: ".$Settings['NodesConfigPath']."/".$sPrimaryGroup);

	If (!Is_Dir($Settings['NodesConfigPath']."/".$sPrimaryGroup)) {
		LogEvent($LocalDebugLevel+2, "Making Save Folder: ".$Settings['NodesConfigPath']."/".$sPrimaryGroup);
		MkDir($Settings['NodesConfigPath']."/".$sPrimaryGroup);
	}
	
	If ( $sPrimaryGroup."-" == SubStr($sComputerName, 0, StrLen($sPrimaryGroup."-")) ) {
		LogEvent($LocalDebugLevel+1, "Group Name is in ComputerName.  Removing Group Name from filename to prevent redundancy");
		$ConfigFile = $Settings['NodesConfigPath'] . "/" . Str_iReplace("-", "/", $sComputerName) . ".ini";
		LogEvent($LocalDebugLevel+2, "New Config File Name: ".$ConfigFile);
#		Print "Config File: ".$Settings['NodesConfigPath'] . "/" . Str_iReplace("-", "/", $sComputerName) . ".ini"."\n";
	} Else {
		$ConfigFile = $Settings['NodesConfigPath'] . "/" . $sPrimaryGroup . "/" . $sComputerName . ".ini";
#		Print "Config File: ".$Settings['NodesConfigPath'] . "/" . $sPrimaryGroup . "/" . $sComputerName . ".ini"."\n";
	}
	
	LogEvent($LocalDebugLevel+1, "Writing Config to File: ".$ConfigFile);
	INI_Write($ConfigFile, "General", "CheckInTime", $sCheckInTime);
	INI_Write($ConfigFile, "General", "ServerStatusNo", $iServerStatusNo);
	INI_Write($ConfigFile, "General", "PrimaryGroup", $sPrimaryGroup);
	
	LogEvent($LocalDebugLevel+1, "Resetting Config File Time to match the Computer Time: ".$sCheckInTime);
	Shell_Exec("touch -d @".StrToTime($sCheckInTime)." ".$ConfigFile);

	If ($Settings['DatabaseCheckin'] == True) { //-> DatabaseCheckIn allows the web interface to monitor the status.
		LogEvent($LocalDebugLevel+1, "DatabaseCheckin is toggled on..");
		OpenDatabase();
		LogEvent($LocalDebugLevel+2, "Searching Database for ".$sPrimaryGroup."/".$sComputerName);
		$Result = $Settings['hDB'] -> Query('SELECT * FROM '.$Settings['DB_NodesTable'].' WHERE ComputerName="'.$sComputerName.'" AND NodeGroup="'.$sPrimaryGroup.'";');
			If ( $Result->num_rows == 1 ) {
			LogEvent($LocalDebugLevel+2, 'Found the Node in the Database.  Updating its StatusNo to "'.$iServerStatusNo.'"');
			$Result -> Data_Seek(0);
			$Row = $Result 	-> Fetch_Assoc();
			$qSQL = 'UPDATE '.$Settings['DB_NodesTable'].' SET StatusNo='.$iServerStatusNo.', CheckInTime="'.$sCheckInTime.'" WHERE ID='.$Row['ID'].';';	
			If ($Settings['hDB'] -> Query($qSQL) !== True) {
				LogEvent(1, "Error: " . $qSQL . "\r\n" . $Settings['hDB']->error, False, False);
			}
		}
		CloseDatabase();
	}

	Return;
}

#==========================================================================================================

?>