// Custom Build Actions for Game04
// This code will be directly executed in the main build script so u can access and declare global variables 

// Include the metadata Function for a diff build
var inlcudeMetaData = buildScriptLocation + "metadataFunctions.js";
eval(ReadFile(inlcudeMetaData, false));

// ---------------Set the project specific globals----------------
var isDiffBuild = false;

// Is this to output a Diff build?
if (WScript.Arguments.Named.Exists("DiffBuild"))
{
	isDiffBuild = true;
}
  			
p4ProjCodeSrc = p4CodeSrc + "depot/G4/dev/Main04/";
p4ProjAssetSrc = p4AssetSrc + "/Game04/";
p4RCSource = p4CodeSrc + "depot/G4/dev/Main04/Bin32/rc/";

// If a asset p4 label was given for an game04 build 
var p4ProjAssetSrcG02 = p4AssetSrc + "/Game02/";
var p4AssetLabelG02 = "";
if(p4AssetLabel != "")
{
	// Use the label for a custom game04 step to sync Game02 asset
	p4AssetLabelG02 = p4AssetLabel;
	// Reset the main p4 asset label so Game04 assets are synced to latest
	p4AssetLabel = "";
}

solutionName = "CryEngine04.sln";		

buildMailingList = "G4_BUILD@crytek.de";

p4_Client = "build_" + computerName + "_" +  project.toLowerCase();

var diffZipPath = "";

if( computerName == "mastercd" ) 
{
	// Choose the drives 
	storageDrive = "\\\\Storage";
	buildDrive = "E:";
	branchDrive = "E:";
	
	storageFolder = storageDrive + "\\builds";
	
	precachedShadersDir = "\\\\mastercd\\ShaderCache";
	
	latestBuildNetworkLink = "\\\\Storage\\builds";
	
	latestBuildServerPath = "\\\\storage\\builds\\Build_tools\\Build_links\\";
}
else if( computerName == "mastercd2" ) 
{
	// Choose the drives 
	storageDrive = "\\\\Storage";
	buildDrive = "G:";
	branchDrive = "G:";
	
	storageFolder = storageDrive + "\\builds";
	
	precachedShadersDir = "\\\\mastercd\\ShaderCache";
	
	latestBuildNetworkLink = "\\\\Storage\\builds";
	
	latestBuildServerPath = "\\\\storage\\builds\\Build_tools\\Build_links\\";
}
else if( computerName == "pc106" )
{
	// Choose the drives 
	storageDrive = "F:";
	buildDrive = "F:";
	branchDrive = "F:";
	
	storageFolder = storageDrive + "\\_builds";
	
	precachedShadersDir = "\\\\mastercd\\ShaderCache";
	
	latestBuildNetworkLink = "\\\\PC106\\_builds";
	
	latestBuildServerPath = buildFilesLocation ;
}
// ---------------------------------------------------------------


function Pre_Init()
{
	buildName += "ALT_";
	if(isDiffBuild && fastBuild)
	{
		var tempNameExtension = nameExtension;
  	nameExtension = "_DiffFromBuild(" + GetBuildNumber(buildFilesLocation + "DiffBuildNumber.txt" , false) + ")";
  	nameExtension += tempNameExtension;
  }
}

function DeleteTemporary_C()
{
	Log("\r\nDeleting Temporary Files");
	DeleteSafely(cppLog,true);
		
	if (fastBuild || DEBUG)
		return;

	if(!DeleteSafely(buildingFolder + "\\*",false) || !DeleteSafely(buildingFolder + "\\*.*",true))
		ErrorExit("Could not clean up the build directory!(" + buildingFolder + ")\r\nThis can have several reasons e.g. a program is accessing the folder. Please solve the problem and restart the build.", aFailEmail , aErrFiles );

	Log("");
  return;
}

function Post_Init()
{
	if(!fastBuild && !DEBUG)
	{
		MakeFolder( buildingFolder + "\\DiffBuild");
		MakeFolder( buildingFolder + "\\DiffBuild\\Game");
		MakeFolder( buildFilesLocation + "old_MetaData" );
		MakeFolder( buildingFolder + "\\DiffBuild\\Game\\Shaders");
		MakeFolder( buildingFolder + "\\DiffBuild\\Game\\Shaders\\Cache");
	}
}

function Pre_GetCode()
{
	//Empty
}

function Post_GetCode()
{
	//Copy ( buildGameDataFolder + "\\Libs\\FlowNodes04" , buildGameDataFolder + "\\Libs\\FlowNodes\\", true , true , true , "" );	//folder is gone
	Copy ( buildGameDataFolder + "\\Scripts04" , buildGameDataFolder + "\\Scripts\\", true , true , true , "" );	
}

function Pre_GetAssets()
{	
	if(p4AssetLabelG02 != "")
	{
		// Game04 needs g02 database to a special label
		PerforceSync(p4ProjAssetSrcG02, p4AssetLabelG02, !fastBuild);
	}
}

function Post_GetAssets()
{
	//Empty
}

function Pre_CompileCode()
{
	//Empty
}

function Post_CompileCode()
{
	//Empty
}

function Pre_ProcessAssets()
{
	//Empty
}

function Post_ProcessAssets()
{
	//Empty
}

function Pre_MakePak()
{
	if(isDiffBuild && fastBuild)
		diffZipPath = buildingFolder + "\\DiffBuild\\Patch_" + GetBuildNumber( buildFilesLocation + "DiffBuildNumber.txt" , false) + "_to_" + buildNumber + ".zip";
}

function MakePakFiles_C()
{
	if(isDiffBuild && fastBuild)
	{	
		CompareMetadata(buildFilesLocation + "metadata.csv", buildFilesLocation + "old_MetaData\\" + "metadata" + "_" + project + buildIdStr + ".csv", buildGameDataFolder, buildFilesLocation + "changedFiles.txt");
		
		if(!DeleteSafely(buildingFolder + "\\DiffBuild\\Patch*.zip", true))
			Log("Could not delete the path zip.");
		
		var loadedChangedFilesFile = ReadFile(buildFilesLocation + "changedFiles.txt", true);
		
		if(loadedChangedFilesFile == "")
			Log("No changed files found in the game directory for DiffBuild.");
		else
		{
			// Create the zDiff_BUILD.pak which contains everything of the Game folder excluding the levels
			PackFolder( buildGameDataFolder, "@" + buildFilesLocation + "changedFiles.txt", buildingFolder + "\\DiffBuild\\Game\\ZDiff_BUILD.pak", 1, buildFilesLocation + "zip_NotInZdiff.lst", "" );
			
			// Create the regular expression
			var re = /^Levels\//i;
			// Create a new filelist with only the levels in it
			if(FilterFileList(buildFilesLocation + "changedFiles.txt", buildFilesLocation + "changedLevelFiles.txt", re, false, "Game/"))
			{
				// Pack the levels into the patch zip
				PackFolder( buildingFolder, "@" + buildFilesLocation + "changedLevelFiles.txt", diffZipPath , 1, "" , "" );
			}
			
			PackFolder( buildingFolder + "\\DiffBuild", buildingFolder + "\\DiffBuild\\Game\\ZDiff_BUILD.pak", diffZipPath, 0, "", "" );
		}		
		
		
		Copy ( precachedShadersDir ,  buildingFolder + "\\DiffBuild\\Game\\Shaders\\Cache\\" , true , false , true , "" );
		PackFolder( buildingFolder + "\\DiffBuild" , buildingFolder + "\\DiffBuild\\Game\\Shaders\\Cache\\d3d9\\*", diffZipPath, 1, "", "" );
		PackFolder( buildingFolder , "Bin32\\*", diffZipPath, 1, buildFilesLocation +"zip_noCommon.lst", "" );
		PackFolder( buildingFolder , "Bin64\\*", diffZipPath, 1, buildFilesLocation +"zip_noCommon.lst", "" );
		PackFolder( buildingFolder , "Tools\\*", diffZipPath, 1, buildFilesLocation +"zip_noCommon.lst", "" );
		PackFolder( buildingFolder , "Editor\\*", diffZipPath, 1, buildFilesLocation +"zip_noCommon.lst", "" );
	}
	else
	{
			MakePakFiles_S();
	}	
}

function Post_MakePak()
{
	//Empty
}

function CopyBuild_C()
{
	if(isDiffBuild && fastBuild)
		FSO.CopyFile( diffZipPath , tempCopyDir + "\\", true);
	else
	{
		CopyBuild_S();
	
		if(buildType != "Code")
			Copy ( buildGameDataFolder+"\\Profiles" , tempCopyDir+"\\Game\\Profiles\\" , true , true , true , buildFilesLocation +"exclude.lst" );
	}
}

function Pre_MakeChangesFiles()
{
	//Empty
}

function Post_MakeChangesFiles()
{
	//Empty
}

function Pre_EndLog()
{
	if(isDiffBuild)
 	{
 		if(fastBuild)
 			succMailBuildTypeExt += "Diff ";	
 		else if(!DEBUG )
 		{
 			DeleteAndCheck(buildFilesLocation + "metadata.csv", true);
 			Log("Generating MetaData for diff builds");
 			GenerateMetadata(buildGameDataFolder, buildFilesLocation + "metadata.csv");
 			// Backup the metadata file 
 			Log("Backup the metadata file");
 			FSO.CopyFile (buildFilesLocation + "metadata.csv", buildFilesLocation + "old_MetaData\\metadata_" + project + buildIdStr + 	"_DiffFrom.csv",true);
 			SaveBuildNumber (buildNumber, buildFilesLocation + "DiffBuildNumber.txt");
 		}
	}
}


//+++++++++Creates a filtered list file out of another one with regularExpressions used as filter to exlcude or include+++++++++++
function FilterFileList(fileIn, fileOut, regExp, exclude, prefix)
{
	var found = false;
	Log("Creating filtered file list: " + fileOut);
	// Read in the file
	var text = ReadFile(fileIn);
	if ( text == "");
		return false;
	
	// Split into array of lines
	var lines = text.split("\r\n");
	
	// clear the input 
	text = null;
	
	// Create the output file
	filterFile = FSO.CreateTextFile(fileOut,true ); 
	
	var lineEnum = new Enumerator(lines);
	
	// Change whether to exlude or include by the matched regular Expression
	if(exclude)
	{
		for (; !lineEnum.atEnd(); lineEnum.moveNext())
		{
			// If the regular expression is NOT FOUND write the line into the new file
			if(lineEnum.item().match(regExp)== null)
			{
				filterFile.WriteLine(prefix + lineEnum.item()+"\n");
				found = true;
			}
		}
	}
	else
	{
		for (; !lineEnum.atEnd(); lineEnum.moveNext())
		{
			// If the regular expression is FOUND write the line into the new file
			if(lineEnum.item().match(regExp)!= null)
			{
				filterFile.WriteLine(prefix + lineEnum.item());
				found = true;
			}
		}
	}
	// Close the output file
	filterFile.Close();
	
	if(found)
		return true;
	else
		return false;
}