@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
::=============================================================================
::TWO empty lines are required for LineFeed to work
set LineFeed=^


::TWO empty lines are required for LineFeed to work
::=============================================================================

:: parameters
:: -noAutotest
:: -debugMode
:: -fastDeploy
:: -fastSteamDev
:: -stable
:: -steamInternal


set batchDir=%~dp0
set criticalError=0
set path=!path!;C:\Windows\system32

:: Date time
set timeBuild=%time%
FOR /F "tokens=1-2 delims= " %%A IN ("%date%") DO (
	set dateBuild=%%B
)


:: Script constants
set Binarize=1
set protection=1
set manualProtection=0
set deploy=1
set buildInternal=1
set buildSteamBeta=1
set buildSteamAlphaLite=0
set buildSteamDedicatedServer=1
set branch=[DEV]
set stableBranch=0
set steamInternal=0
set debugMode=0
set fastDeploy=0
set fastSteamDev=0
:: Enable autotest
set autotest=1
:: Autotest must success
set autotestSuccess=1
set autotestFps=1
set autotestSecondary=1
set wantSendToNG=1
set autotestStatistics=1
set JNIBuild=0
set buildWithIncrediBuild=1
set buildWithIBPreset=1
set rebuild=/rebuild
set sendToWebDAV=1

:: Set this for project
set productName=Arma3
set outputBuildInternalName=Arma3Int_DX11
set outputAppInternalName=Arma3Int_DX11
set outputBuildSteamBetaName=Arma3Retail_DX11
set outputAppSteamBetaName=arma3
set outputBuildSteamAlphaLiteName=Arma3Demo_DX11
set outputAppSteamAlphaLiteName=arma3demo
set outputBuildSteamDedicatedServerName=Arma3Retail_Server
set outputAppSteamDedicatedServerName=arma3server


:: Build params
set devenv="c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.com"
set incredibuild="c:\Program Files (x86)\Xoreax\IncrediBuild\BuildConsole.exe"
set sourcePath=c:\w\C_Branch\Poseidon\Futura\
set Arma3sln=%sourcePath%Arma3_2012.sln
set buildVer=DefaultVersion
set buildInternalCfg="Release_DX11|Win32"
set buildSteamBetaCfg="Retail_DX11|Win32"
set buildSteamAlphaLiteCfg="Retail_Demo_DX11|Win32"
set buildSteamDedicatedServerCfg="Retail Server|Win32"
set buildDir=C:\O\Arma3\
set buildLog=%batchDir%BuildLogIB.txt

:: Protection
set steamDrmTool=c:\Bis\Build\Steam\drmtool.exe
set signTool="c:\Bis\sign\sign.bat"
set steamBetaAppId=107410
set steamAlphaLiteAppId=228800
set steamInternalAppId=228820

:: Data and code paths
set autotestDir=O:\Arma3.Autotest\
set outputInternal=O:\Arma3.Internal\
set outputSteamBetaDir=O:\Arma3.Steam-Dev\
set outputSteamAlphaLiteDir=O:\Arma3.SteamAlphaLite-Dev\
set outputSteamDedicatedServerDir=O:\Arma3.SteamDedicatedServer-Dev\
set productBinAlphaDir=x:\ArmA2_Expansion\Futura\Dta\
set productBinAlphaLiteDir=x:\Arma3_Demo\Dta\
set logsDstPath=O:\Arma3.Logs\
set exeBackupDir=%logsDstPath%
set networkLogsPath=//Builder/O/Arma3.Logs
set oldExeForManualProtection=Arma3int.exe
set autotestExe=%outputBuildInternalName%.exe
set autotestSteamBetaExe=%outputBuildSteamBetaName%.exe
set mainAutotestCfg=a3\missions_design_F\autotest\autotest_main.cfg
set secondAutotestCfg=a3\missions_design_F\autotest\autotest_secondary.cfg
set fpsAutotestCfg=a3\missions_design_F\autotest\autotest_fps.cfg
set mainAutotestSteamBetaCfg=a3\missions_design_F\autotest\autotest_main_retail.cfg
set rptLogName=%outputBuildInternalName%
set rptSteamBetaLogName=%outputBuildSteamBetaName%
set logsSrcPath="c:\Users\%username%\AppData\Local\ArmA 3\"
for %%I in (%logsSrcPath%) do (
	set rptLogPath="%%~I%rptLogName%.rpt"
	set oldrptLogPath="%%~I%rptLogName%_old.rpt"
	set minidump="%%~I%rptLogName%.mdmp"
	set rptSteamBetaLogPath="%%~I%rptSteamBetaLogName%.rpt"
	set oldrptSteamBetaLogPath="%%~I%rptSteamBetaLogName%_old.rpt"
	set minidumpSteamBeta="%%~I%rptSteamBetaLogName%.mdmp"
	set debugLogPath="%%~Idebug.log"
)
set webDAVSteamBetaPath=https://beta3.bistudio.com/files/a3exe/Arma3/
set webDAVSteamBetaDedicatedServerPath=https://beta3.bistudio.com/files/a3exe/Arma3DedicatedServer/


:: Get parameters
:loopParams
if [%1]==[] goto endParams
if [%1]==[-noAutotest] set autotest=0
if [%1]==[-debugMode] set debugMode=1
if [%1]==[-fastDeploy] set fastDeploy=1
if [%1]==[-fastSteamDev] set fastSteamDev=1
if [%1]==[-stable] set stableBranch=1
if [%1]==[-steamInternal] set steamInternal=1
shift
goto loopParams
:endParams


:: Stable branch (Steam builds. Stable branch)
if [%stableBranch%]==[1] (
	set buildInternal=0
	set buildSteamBeta=1
	set buildSteamAlphaLite=0
	set buildSteamDedicatedServer=1
	set outputSteamBetaDir=O:\Arma3.Steam-Stable\
	set outputSteamAlphaLiteDir=O:\Arma3.SteamAlphaLite-Stable\
	set outputSteamDedicatedServerDir=O:\Arma3.SteamDedicatedServer-Stable\
	set autotest=1
	set autotestFps=0
	set autotestSecondary=0
	set autotestStatistics=0
	set branch=[STEAM-RC]
	set sendToWebDAV=0
	set sourcePath=c:\w\C_Branch\Poseidon\Futura_Stable\
	set Arma3sln=!sourcePath!Arma3_2012.sln
)

:: Arma 3 Internal on Steam
if [%steamInternal%]==[1] (
	set buildInternal=0
	set buildSteamBeta=1
	set buildSteamAlphaLite=0
	set buildSteamDedicatedServer=0
	set outputBuildSteamBetaName=Arma3Retail_Internal_DX11
	set outputAppSteamBetaName=arma3
	set steamBetaAppId=228820
	set buildSteamBetaCfg="Retail_Internal_DX11|Win32"
	set outputSteamBetaDir=O:\Arma3.SteamInternal-Dev\
	set autotestSteamBetaExe=!outputBuildSteamBetaName!.exe
	set autotest=1
	set autotestFps=0
	set autotestSecondary=0
	set autotestStatistics=0
	set rptSteamBetaLogName=!outputBuildSteamBetaName!
	for %%I in (!logsSrcPath!) do (
		set rptSteamBetaLogPath="%%~I!rptSteamBetaLogName!.rpt"
		set oldrptSteamBetaLogPath="%%~I!rptSteamBetaLogName!_old.rpt"
		set minidumpSteamBeta="%%~I!rptSteamBetaLogName!.mdmp"
	)
	set sendToWebDAV=1
	set webDAVSteamBetaPath=https://beta3.bistudio.com/files/a3exe/Arma3SteamInternal/
)

:: Debug mode
if [%debugMode%]==[1] (
	set wantSendToNG=0
	set buildInternal=1
	set buildSteamBeta=0
	set buildSteamAlphaLite=0
	set buildSteamDedicatedServer=0
	set autotest=1
	set autotestStatistics=0
	set deploy=0
	set protection=1
	set rebuild=/build
	set mainAutotestCfg=a3\missions_design_F\autotest\autotest_fast.cfg
	set secondAutotestCfg=a3\missions_design_F\autotest\autotest_fast.cfg
	set fpsAutotestCfg=a3\missions_design_F\autotest\autotest_fast.cfg
)

:: Fast deploy (main autotest, no other build)
if [%fastDeploy%]==[1] (
	set buildInternal=1
	set buildSteamBeta=0
	set buildSteamAlphaLite=0
	set buildSteamDedicatedServer=0
	set autotest=1
	set autotestFps=0
	set autotestSecondary=0
	set autotestStatistics=0
	set rebuild=/build
)

:: Fast Steam deploy (Only Steam Dev, no other build)
if [%fastSteamDev%]==[1] (
	set buildInternal=0
	set buildSteamBeta=1
	set buildSteamAlphaLite=0
	set buildSteamDedicatedServer=1
	set autotest=1
	set autotestFps=0
	set autotestSecondary=0
	set autotestStatistics=0
	set rebuild=/build
	set branch=[STEAM-DEV]
)

:: Tools path
set svn=c:\Bis\Subversion\bin\svn
set python=c:\Python27\python.exe
set SendToNG=c:\bis\build\SendToNG.bat
set bedarDir=c:\bis\bedar\
set perl=c:\Perl\bin\perl.exe
set curl=b:\curl\ssl\curl.exe

set logLastLinesCount=35


:: Zdrojova cesta k adonum Arma3
set armaFuturaAddons=x:\ArmA2_Expansion\Futura


cd /d %batchDir%


echo ----------------------------------------------------------------------
echo --- %productName% (%buildVer%) build ---------------------------------
echo ---------------------------------------- %dateBuild% %timeBuild% -----
echo parameters:
echo   - branch: %branch%
echo   - buildVer: %buildVer%
if [%debugMode%]==[1] (
echo   - debugMode: %debugMode%
)
if [!buildInternal!]==[1] (
echo   - buildInternal: %buildInternal%
echo   - buildInternalCfg: %buildInternalCfg%
echo   - outputAppInternalName: %outputAppInternalName%.exe
echo   - outputInternal: %outputInternal%
)
if [!buildSteamBeta!]==[1] (
echo   - buildSteamBeta: %buildSteamBeta%
echo   - buildSteamBetaCfg: %buildSteamBetaCfg%
echo   - outputAppSteamBetaName: %outputAppSteamBetaName%.exe
echo   - outputSteamBetaDir: %outputSteamBetaDir%
)
if [!buildSteamAlphaLite!]==[1] (
echo   - buildSteamAlphaLite: %buildSteamAlphaLite%
echo   - buildSteamAlphaLiteCfg: %buildSteamAlphaLiteCfg%
echo   - outputAppSteamAlphaLiteName: %outputAppSteamAlphaLiteName%.exe
echo   - outputSteamAlphaLiteDir: %outputSteamAlphaLiteDir%
)
if [!buildSteamDedicatedServer!]==[1] (
echo   - buildSteamDedicatedServer: %buildSteamDedicatedServer%
echo   - buildSteamDedicatedServerCfg: %buildSteamDedicatedServerCfg%
echo   - outputAppSteamDedicatedServerName: %outputAppSteamDedicatedServerName%.exe
echo   - outputSteamDedicatedServerDir: %outputSteamDedicatedServerDir%
)
echo   - buildDir: %buildDir%
echo   - autotestDir: %autotestDir%
echo   - protection: %protection%
echo   - autotest: %autotest%
echo   - autotestFps: %autotestFps%
echo   - autotestSecondary: %autotestSecondary%
echo   - build switch: %rebuild%
echo ----------------------------------------------------------------------


::=============================================================================
:: Update sources from svn
::=============================================================================
echo Getting sources revision %SVNrevisionNo% ...
%svn% update --non-interactive %sourcePath% 2> %batchDir%svnUpdateError.txt
if errorlevel 1 goto svnUpdateFailed

:: Get SVN info
pushd
%svn% info %sourcePath% > %batchDir%svninfo_uncensored.txt
echo SVN Info:
type svninfo_uncensored.txt

:: Set SVNrevisionNo
%perl% %batchDir%getLastChangedRevisionNumber.pl %batchDir%svninfo_uncensored.txt > %batchDir%svninfoRevNo.txt
::%perl% %batchDir%getRevisionNumber.pl %batchDir%svninfo_uncensored.txt > %batchDir%svninfoRevNo.txt
set /p SVNrevisionNo=<%batchDir%svninfoRevNo.txt

:: Set full path to autotest logs and backup dir
set timeBuildHour=%timeBuild:~0,2%
set timeBuildMinute=%timeBuild:~3,2%
set logDirName=%SVNrevisionNo%-%DATE:~3%-%timeBuildHour: =0%.%timeBuildMinute: =0%-%branch%
set logsDstFullPath=%logsDstPath%%logDirName%
set exeBackupFullPath=%exeBackupDir%%logDirName%
md %logsDstFullPath%
if not [%logsDstFullPath%]==[%exeBackupFullPath%] md %exeBackupFullPath%
set exeBackupFullPathBuildInternal=%exeBackupFullPath%\buildInternal
set exeBackupFullPathBuildSteamBeta=%exeBackupFullPath%\BuildSteamBeta
set exeBackupFullPathBuildSteamAlphaLite=%exeBackupFullPath%\BuildSteamAlphaLite
set exeBackupFullPathBuildSteamDedicatedServer=%exeBackupFullPath%\BuildSteamDedicatedServer
if [%buildInternal%]==[1] md %exeBackupFullPathBuildInternal%
if [%buildSteamBeta%]==[1] md %exeBackupFullPathBuildSteamBeta%
if [%buildSteamAlphaLite%]==[1] md %exeBackupFullPathBuildSteamAlphaLite%
if [%buildSteamDedicatedServer%]==[1] md %exeBackupFullPathBuildSteamDedicatedServer%

REM SVN revision - used in reports (NG etc.) - can be assembled from svninfoRevNo.txt
::filter.pl -f -t %batchDir%svninfo_uncensored.txt revision > %batchDir%svninfo.txt
popd


:: Create buildNo.h
echo Create buildNo.h
call %batchDir%makeBuildNoH.bat
copy %batchDir%buildNo.h %sourcePath%\..

::=============================================================================
:: Build with Incredibuild preset system (parallel building)
::=============================================================================
if [!buildWithIncrediBuild!]==[0] goto noBuildWithIBPreset
if [!buildWithIBPreset!]==[0] goto noBuildWithIBPreset

!incredibuild! /Enable > nul

set generatedBuildPreset=GeneratedBuildPreset
set buildIBPresetFile=!Arma3sln:~,-4!.ib_preset

set InternalBuildSuccessful=0
set SteamBetaBuildSuccessful=0
set SteamAlphaLiteBuildSuccessful=0
set SteamDedicatedServerBuildSuccessful=0

echo *** Creating Incredibuild preset file !buildIBPresetFile! ...
set buildIBPreset=
set buildIBPreset=!buildIBPreset!^<Presets^>!LineFeed!
set buildIBPreset=!buildIBPreset!	^<Preset Name="!generatedBuildPreset!" FormatVersion="1"^>!LineFeed!

set buildIBCfgProjectInfo=			^<Project Name="cfg2012" RelativePath="cfg\cfg2012.vcxproj" MSBuildName="cfg2012"/^>!LineFeed!
set buildIBLibProjectInfo=			^<Project Name="lib2012" RelativePath="lib\lib2012.vcxproj" MSBuildName="lib2012"/^>!LineFeed!
set buildIBUnitTestProjectInfo=			^<Project Name="unittests" RelativePath="unittests\unittests.vcxproj" MSBuildName="unittests"/^>!LineFeed!

if [!buildInternal!]==[1] call:funcGenerateBuildPreset !buildInternalCfg!
if [!buildSteamBeta!]==[1] call:funcGenerateBuildPreset !buildSteamBetaCfg!
if [!buildSteamAlphaLite!]==[1] call:funcGenerateBuildPreset !buildSteamAlphaLiteCfg!
if [!buildSteamDedicatedServer!]==[1] call:funcGenerateBuildPreset !buildSteamDedicatedServerCfg!

set buildIBPreset=!buildIBPreset!	^</Preset^>!LineFeed!
set buildIBPreset=!buildIBPreset!^</Presets^>
echo !buildIBPreset! > !buildIBPresetFile!

echo *** Building Incredibuild preset ...
!incredibuild! !Arma3sln! !rebuild! /preset="!generatedBuildPreset!" /log="!buildLog!"
echo errorlevel %errorlevel%
if errorlevel 1 goto buildFail
echo Build of Incredibuild preset finished successfully

:: Was at least one configuration built
set somethingWasBuilt=0
if [!buildInternal!]==[1] set somethingWasBuilt=1
if [!buildSteamBeta!]==[1] set somethingWasBuilt=1
if [!buildSteamAlphaLite!]==[1] set somethingWasBuilt=1
if [!buildSteamDedicatedServer!]==[1] set somethingWasBuilt=1

if [!somethingWasBuilt!]==[1] (
	call:funcGenerateBinCfg
)

:: Generate shaders and export java interface
if [!buildInternal!]==[1] (
	call:funcGenerateShaders !outputBuildInternalName!
	call:funcCreateBinPbo !exeBackupFullPathBuildInternal!
)
if [!buildSteamBeta!]==[1] (
	call:funcGenerateShaders !outputBuildSteamBetaName!
	call:funcCreateBinPbo !exeBackupFullPathBuildSteamBeta!
)
if [!buildSteamAlphaLite!]==[1] (
	call:funcGenerateShaders !outputBuildSteamAlphaLiteName!
	call:funcCreateBinPbo !exeBackupFullPathBuildSteamAlphaLite!
)
if [!buildSteamDedicatedServer!]==[1] (
	:: We don't want any shaders in server configuration
  del /q /f !buildDir!bin\*.shdc 2>nul
	call:funcCreateBinPbo !exeBackupFullPathBuildSteamDedicatedServer!
)

:: All ok, set flag
if [!buildInternal!]==[1] set InternalBuildSuccessful=1
if [!buildSteamBeta!]==[1] set SteamBetaBuildSuccessful=1
if [!buildSteamAlphaLite!]==[1] set SteamAlphaLiteBuildSuccessful=1
if [!buildSteamDedicatedServer!]==[1] set SteamDedicatedServerBuildSuccessful=1

goto buildDone
:noBuildWithIBPreset

::=============================================================================
:: Build configurations
::=============================================================================
set InternalBuildSuccessful=0
if [!buildInternal!]==[0] (
	call:funcBuildConfiguration Internal !buildInternalCfg! !exeBackupFullPathBuildInternal! !outputBuildInternalName!
	:: All ok, set flag
	set InternalBuildSuccessful=1
)

set SteamBetaBuildSuccessful=0
if [!buildSteamBeta!]==[0] (
	call:funcBuildConfiguration SteamBeta !buildSteamBetaCfg! !exeBackupFullPathBuildSteamBeta! !outputBuildSteamBetaName!
	:: All ok, set flag
	set SteamBetaBuildSuccessful=1
)

set SteamAlphaLiteBuildSuccessful=0
if [!buildSteamAlphaLite!]==[0] (
	call:funcBuildConfiguration SteamAlphaLite !buildSteamAlphaLiteCfg! !exeBackupFullPathBuildSteamAlphaLite! !outputBuildSteamAlphaLiteName!
	:: All ok, set flag
	set SteamAlphaLiteBuildSuccessful=1
)

set SteamDedicatedServerBuildSuccessful=0
if [!buildSteamDedicatedServer!]==[0] (
	call:funcBuildConfiguration SteamDedicatedServer !buildSteamDedicatedServerCfg! !exeBackupFullPathBuildSteamDedicatedServer!
	:: All ok, set flag
	set SteamDedicatedServerBuildSuccessful=1
)

:buildDone

::=============================================================================
:: Build Allocators
::=============================================================================
echo *** Building Allocators...
del /q %buildLog% 2>nul
echo JEMalloc
%devenv% %sourcePath%Allocators\JEMalloc\JEMalloc_bi.sln /build "Release|Win32" /Out "%buildLog%"
if errorlevel 1 set allocBuildFailed=1
echo NedMalloc
%devenv% %sourcePath%Allocators\NedMalloc\NedMalloc_bi.sln /build "Release|Win32" /Out "%buildLog%"
if errorlevel 1 set allocBuildFailed=1
echo TCMalloc
%devenv% %sourcePath%Allocators\TCMalloc\TCMalloc.sln /build "Release|Win32" /Out "%buildLog%"
if errorlevel 1 set allocBuildFailed=1
echo TBB3
%devenv% %sourcePath%Allocators\TBB3\tbb\build\vsproject\makefile.sln /build "Release|Win32" /Out "%buildLog%"
if errorlevel 1 set allocBuildFailed=1
echo TBB4
%devenv% %sourcePath%Allocators\TBB4\tbb\build\vsproject\makefile.sln /build "Release|Win32" /Out "%buildLog%"
if errorlevel 1 set allocBuildFailed=1

if (%allocBuildFailed%)==(1) goto AllocatorBuildFailed

echo Build finished successfully
xcopy /y %sourcePath%Allocators\*.dll %buildDir%dll\

goto noBuildAllocators

:AllocatorBuildFailed
if [%wantSendToNG%]==[1] (
	call %SendToNG% "%branch% Allocator BUILD failed." %buildLog%
)

:noBuildAllocators


::=============================================================================
:: protection
::=============================================================================
if [%protection%]==[0] goto noProtection

echo *** Protecting exe...

:: Automatic steam protection
if [!InternalBuildSuccessful!]==[1] call:funcProtectSteam !buildDir!!outputBuildInternalName!.exe !steamInternalAppId!
if [!SteamBetaBuildSuccessful!]==[1] call:funcProtectSteam !buildDir!!outputBuildSteamBetaName!.exe !steamBetaAppId!
if [!SteamAlphaLiteBuildSuccessful!]==[1] call:funcProtectSteam !buildDir!!outputBuildSteamAlphaLiteName!.exe !steamAlphaLiteAppId!
:: No protection for dedicated server

:noProtection
goto protectionOk

:protectionOk

::=============================================================================
:: Sign app .exe
::=============================================================================
echo *** Sign app exe

if [%InternalBuildSuccessful%]==[1] call:funcSignAppExe !outputBuildInternalName!
if [%SteamBetaBuildSuccessful%]==[1] call:funcSignAppExe !outputBuildSteamBetaName!
if [%SteamAlphaLiteBuildSuccessful%]==[1] call:funcSignAppExe !outputBuildSteamAlphaLiteName!
if [%SteamDedicatedServerBuildSuccessful%]==[1] call:funcSignAppExe !outputBuildSteamDedicatedServerName!

::=============================================================================
:: Backup data (.exe, .map, .pdb) and Rename in backup directory build .exe to app .exe
::=============================================================================
echo +++ Backup new exe and debug data and rename build exe to app exe in backup directory

if [!InternalBuildSuccessful!]==[1] call:funcBackupExeMapPdb !outputBuildInternalName! !outputAppInternalName! !exeBackupFullPathBuildInternal!
if [!SteamBetaBuildSuccessful!]==[1] call:funcBackupExeMapPdb !outputBuildSteamBetaName! !outputAppSteamBetaName! !exeBackupFullPathBuildSteamBeta!
if [!SteamAlphaLiteBuildSuccessful!]==[1] call:funcBackupExeMapPdb !outputBuildSteamAlphaLiteName! !outputAppSteamAlphaLiteName! !exeBackupFullPathBuildSteamAlphaLite!
if [!SteamDedicatedServerBuildSuccessful!]==[1] call:funcBackupExeMapPdb !outputBuildSteamDedicatedServerName! !outputAppSteamDedicatedServerName! !exeBackupFullPathBuildSteamDedicatedServer!


::=============================================================================
:: Update data
::=============================================================================
echo +++ Copy %productName% data to %autotestDir%
robocopy %armaFuturaAddons% %autotestDir% *.* /S /E /NP
robocopy x:\fp\Dta %autotestDir%\Dta *.pbo /S /E /NP
xcopy /y x:\ArmA2_Expansion\Futura\Dta\languagecore_f.* %autotestDir%\Dta\

if [%autotest%]==[1] (
	if [%InternalBuildSuccessful%]==[1] (
		copy %buildDir%%outputBuildInternalName%.exe %autotestDir% /y
		copy %buildDir%%outputBuildInternalName%.map %autotestDir% /y
		copy %buildDir%%outputBuildInternalName%.pdb %autotestDir% /y
	)
	if [%SteamBetaBuildSuccessful%]==[1] (
		copy %buildDir%%outputBuildSteamBetaName%.exe %autotestDir% /y
		copy %buildDir%%outputBuildSteamBetaName%.map %autotestDir% /y
		copy %buildDir%%outputBuildSteamBetaName%.pdb %autotestDir% /y
	)
)
copy %buildDir%*.dll %autotestDir% /y
xcopy /y %buildDir%\dll\*.* %autotestDir%dll\

copy %batchDir%svninfo_uncensored.txt %autotestDir%\svn_info.txt /y
echo done


::=============================================================================
:: Autotest beginning
::=============================================================================
set autotestErrorLevel=0
if not [%autotest%]==[1] goto noAutotest

del /q %batchDir%autotestResult.txt 2>nul
del /q %batchDir%autotestInfo.txt 2>nul
del /q %batchDir%autotestInfo2.txt 2>nul
del /q %batchDir%autotestFps.txt 2>nul
del /q %batchDir%rptLastLines.txt 2>nul

set mainAutotestLogsDir=Autotest.main\
set fpsAutotestLogsDir=Autotest.fps\
set secondAutotestLogsDir=Autotest.secondary\

set mainAutotestSteamBetaLogsDir=AutotestSteamBeta.main\

::=============================================================================
:: Autotest internal
::=============================================================================
if not [%InternalBuildSuccessful%]==[1] goto noAutotestInternal

::-----------------------------------------------------------------------------
:: Main Autotest
set autotestName=Main autotest
echo *** %autotestName% started
if [!Binarize!]==[1] copy !exeBackupFullPathBuildInternal!\bin.pbo* !autotestDir!\Dta /y
:: put right steam appid before autotest
echo !steamInternalAppId!> !autotestDir!steam_appid.txt
:: delete old files (delete all .rpt" by removing .rpt" and add *.rpt" , also for .mdmp, .bidmp)
del /q %rptLogPath:.rpt"=%*.rpt" 2>nul
del /q %minidump:.mdmp"=%*.mdmp" 2>nul
del /q %minidump:.mdmp"=%*.bidmp" 2>nul
del /q %debugLogPath% 2>nul
:: start autotest
cd /d %autotestDir%
%autotestExe% -window -nosplash -mod=design;delta -autotest=%mainAutotestCfg%
set lastErrorLevel=%errorlevel%
set autotestErrorLevel=%lastErrorLevel%
echo Finished with errorlevel %lastErrorLevel%
echo %autotestName% finished with errorlevel=%lastErrorLevel% >> %batchDir%autotestResult.txt

::rename specialized .rpt name to standardized (rename need just file name as second parameter)
for %%I in (%rptLogPath:.rpt"=%*.rpt") do ren "%%I" %rptLogName%.rpt
for %%I in (%minidump:.mdmp"=%*.mdmp") do ren "%%I" %rptLogName%.mdmp

:: create autotest info
call:funcCreateAutotestInfo
if not %lastErrorLevel%==0 echo *** %autotestName% failed. Last RPT lines *** >> %batchDir%rptLastLines.txt
if not %lastErrorLevel%==0 %perl% %bedarDir%autotestresult\lastlines.pl %rptLogPath% "%logLastLinesCount%" 1>> %batchDir%rptLastLines.txt 2>&1

:: create autotest statistics
if [%autotestStatistics%]==[1] (
	echo *** Create bedar_stat.rpt
	del /q %autotestDir%bedar_stat.rpt 2>nul
	call %bedarDir%filter\extract_rpt.bat %logsSrcPath% %outputBuildInternalName% %autotestDir%
	%perl% %bedarDir%autotestresult\at-result.pl %rptLogPath% 1> %batchDir%at-result.txt 2>&1
)

:: Copy logs
call:funcCopyCrashLogs %mainAutotestLogsDir%
copy %rptLogPath% %oldrptLogPath% /y

:: if autotest failed, do not start another autotests
if not [%autotestErrorLevel%]==[0] if [%autotestSuccess%]==[1] goto autotestEnd


if not [%autotestFps%]==[1] goto noAutotest_Fps
::-----------------------------------------------------------------------------
:: FPS Autotest
set autotestName=FPS autotest
echo *** %autotestName% started
!incredibuild! /Disable > nul
:: put right steam appid before autotest
echo !steamInternalAppId!> !autotestDir!steam_appid.txt
:: delete old files (delete all .rpt" by removing .rpt" and add *.rpt" , also for .mdmp, .bidmp)
del /q %rptLogPath:.rpt"=%*.rpt" 2>nul
del /q %minidump:.mdmp"=%*.mdmp" 2>nul
del /q %minidump:.mdmp"=%*.bidmp" 2>nul
del /q %debugLogPath% 2>nul

cd /d %autotestDir%
%autotestExe% -window -nosplash -mod=design;delta -nologs -autotest=%fpsAutotestCfg%
set lastErrorLevel=%errorlevel%
set autotestErrorLevel=%lastErrorLevel%
echo Finished with errorlevel %lastErrorLevel%
echo %autotestName% finished with errorlevel=%lastErrorLevel% >> %batchDir%autotestResult.txt

!incredibuild! /Enable > nul

::rename specialized .rpt name to standardized (rename need just file name as second parameter)
for %%I in (%rptLogPath:.rpt"=%*.rpt") do ren "%%I" %rptLogName%.rpt
for %%I in (%minidump:.mdmp"=%*.mdmp") do ren "%%I" %rptLogName%.mdmp

:: create autotest info
call:funcCreateAutotestInfo
if not %lastErrorLevel%==0 echo *** %autotestName% failed. Last RPT lines *** >> %batchDir%rptLastLines.txt
if not %lastErrorLevel%==0 %perl% %bedarDir%autotestresult\lastlines.pl %rptLogPath% "%logLastLinesCount%" 1>> %batchDir%rptLastLines.txt 2>&1

:: Copy crash info
if not [%lastErrorLevel%]==[0] call:funcCopyCrashLogs %fpsAutotestLogsDir%

:: create FPS result
echo %autotestName% result: >> %batchDir%autotestFps.txt
%perl% %bedarDir%deriveFPS.pl %rptLogPath% %batchDir%autotestFps.txt
echo. >> %batchDir%autotestFps.txt

:: if autotest failed, do not start another autotests
if not [%autotestErrorLevel%]==[0] if [%autotestSuccess%]==[1] goto autotestEnd

:noAutotest_Fps


if not [%autotestSecondary%]==[1] goto noAutotest_Secondary
::-----------------------------------------------------------------------------
:: Secondary Autotest
set autotestName=Secondary autotest
echo *** %autotestName% started
:: put right steam appid before autotest
echo !steamInternalAppId!> !autotestDir!steam_appid.txt
:: delete old files (delete all .rpt" by removing .rpt" and add *.rpt" , also for .mdmp, .bidmp)
del /q %rptLogPath:.rpt"=%*.rpt" 2>nul
del /q %minidump:.mdmp"=%*.mdmp" 2>nul
del /q %minidump:.mdmp"=%*.bidmp" 2>nul
del /q %debugLogPath% 2>nul

:: start autotest
cd /d %autotestDir%
%autotestExe% -window -nosplash -mod=design;delta -autotest=%secondAutotestCfg%
set lastErrorLevel=%errorlevel%
echo Finished with errorlevel %lastErrorLevel%
echo %autotestName% finished with errorlevel=%lastErrorLevel% >> %batchDir%autotestResult.txt

::rename specialized .rpt name to standardized (rename need just file name as second parameter)
for %%I in (%rptLogPath:.rpt"=%*.rpt") do ren "%%I" %rptLogName%.rpt
for %%I in (%minidump:.mdmp"=%*.mdmp") do ren "%%I" %rptLogName%.mdmp

:: create autotest info
call:funcCreateAutotestInfo
if not %lastErrorLevel%==0 echo *** %autotestName% failed. Last RPT lines *** >> %batchDir%rptLastLines.txt
if not %lastErrorLevel%==0 %perl% %bedarDir%autotestresult\lastlines.pl %rptLogPath% "%logLastLinesCount%" 1>> %batchDir%rptLastLines.txt 2>&1

:: Copy crash info (report crash info every time)
::if not [%lastErrorLevel%]==[0] call:funcCopyCrashLogs %secondAutotestLogsDir%
call:funcCopyCrashLogs %secondAutotestLogsDir%

:noAutotest_Secondary

:noAutotestInternal

::=============================================================================
:: Autotest SteamBeta
::=============================================================================
if not [%SteamBetaBuildSuccessful%]==[1] goto noAutotestSteamBeta

::-----------------------------------------------------------------------------
:: Main Autotest
set autotestName=Main autotest Steam Beta
echo *** %autotestName% started
if [!Binarize!]==[1] copy !exeBackupFullPathBuildSteamBeta!\bin.pbo* !autotestDir!\Dta /y
:: put right steam appid before autotest
echo !steamBetaAppId!> !autotestDir!steam_appid.txt
:: delete old files (delete all .rpt" by removing .rpt" and add *.rpt" , also for .mdmp, .bidmp)
del /q %rptSteamBetaLogPath:.rpt"=%*.rpt" 2>nul
del /q %minidumpSteamBeta:.mdmp"=%*.mdmp" 2>nul
del /q %minidumpSteamBeta:.mdmp"=%*.bidmp" 2>nul
del /q %debugLogPath% 2>nul
:: start autotest
cd /d %autotestDir%
%autotestSteamBetaExe% -window -nosplash -mod=design;delta -autotest=%mainAutotestSteamBetaCfg%
set lastErrorLevel=%errorlevel%
set autotestErrorLevel=%lastErrorLevel%
echo Finished with errorlevel %lastErrorLevel%
echo %autotestName% finished with errorlevel=%lastErrorLevel% >> %batchDir%autotestResult.txt

::rename specialized .rpt name to standardized (rename need just file name as second parameter)
for %%I in (%rptSteamBetaLogPath:.rpt"=%*.rpt") do ren "%%I" %rptSteamBetaLogName%.rpt
for %%I in (%minidumpSteamBeta:.mdmp"=%*.mdmp") do ren "%%I" %rptSteamBetaLogName%.mdmp

:: create autotest info
call:funcCreateAutotestInfo
if not %lastErrorLevel%==0 echo *** %autotestName% failed. Last RPT lines *** >> %batchDir%rptLastLines.txt
if not %lastErrorLevel%==0 %perl% %bedarDir%autotestresult\lastlines.pl %rptSteamBetaLogPath% "%logLastLinesCount%" 1>> %batchDir%rptLastLines.txt 2>&1

:: Copy logs
call:funcCopySteamBetaCrashLogs %mainAutotestSteamBetaLogsDir%
copy %rptSteamBetaLogPath% %oldrptSteamBetaLogPath% /y

:: if autotest failed, do not start another autotests
if not [%autotestErrorLevel%]==[0] if [%autotestSuccess%]==[1] goto autotestEnd

:noAutotestSteamBeta

:autotestEnd

::=============================================================================
:: Create full autotest result
::=============================================================================
echo *** Create autotestResult.txt

echo. >> %batchDir%autotestResult.txt

if [%InternalBuildSuccessful%]==[1] (
	:: Full rpt
	echo Full RPT file: >> %batchDir%autotestResult.txt
	echo file:///%networkLogsPath%/%logDirName%/%mainAutotestLogsDir%%rptLogName%.RPT >> %batchDir%autotestResult.txt
	echo. >> %batchDir%autotestResult.txt
	:: Debug log
	echo Debug log: >> %batchDir%autotestResult.txt
	echo file:///%networkLogsPath%/%logDirName%/%mainAutotestLogsDir%debug.log >> %batchDir%autotestResult.txt
	echo. >> %batchDir%autotestResult.txt
)

if [%SteamBetaBuildSuccessful%]==[1] (
	:: Full rpt
	echo Full RPT file: >> %batchDir%autotestResult.txt
	echo file:///%networkLogsPath%/%logDirName%/%mainAutotestSteamBetaLogsDir%%rptSteamBetaLogName%.RPT >> %batchDir%autotestResult.txt
	echo. >> %batchDir%autotestResult.txt
)

:: Statistics
if [%autotestStatistics%]==[1] (
	echo Autotest RPT statistics sorted by occurrence: >> %batchDir%autotestResult.txt
	echo file:///%networkLogsPath%/%logDirName%/bedar_stat.rpt >> %batchDir%autotestResult.txt
	echo. >> %batchDir%autotestResult.txt
)

:: Autotest result
if [%autotestStatistics%]==[1] (
	type %batchDir%at-result.txt >> %batchDir%autotestResult.txt
	echo. >> %batchDir%autotestResult.txt
)

:: Last RPT lines
if not [%autotestErrorLevel%]==[0] (
	echo RPT last %logLastLinesCount% lines >> %batchDir%autotestResult.txt
	echo ===============================================================================  >> %batchDir%autotestResult.txt
	type %batchDir%rptLastLines.txt >> %batchDir%autotestResult.txt
	echo. >> %batchDir%autotestResult.txt
)

:: Autotest info
echo. >> %batchDir%autotestResult.txt
type %batchDir%autotestInfo.txt >> %batchDir%autotestResult.txt
echo. >> %batchDir%autotestResult.txt
type %batchDir%autotestInfo2.txt >> %batchDir%autotestResult.txt


:: if autotest failed and must success, report failed
if not [%autotestErrorLevel%]==[0] if [%autotestSuccess%]==[1] goto autotestFailed

:autotestOk
echo Autotest finished successfully

:: FPS statistic
copy %batchDir%autotestFps.txt %logsDstFullPath% /y
:: If build hour is greater or equal of 5:00 then behave as DAY build (fps not in graph)
set timeHourCreating=!time:~0,2!
if !timeHourCreating! GEQ 5 (
	ren !logsDstFullPath!\autotestFps.txt autotestFps-DAY.txt
)

if [%wantSendToNG%]==[1] (
	:: Create FPS graph
	del /q %batchDir%fpsgraph.png 2>nul
	%python% %batchDir%bdrgraph.py --output %batchDir%fpsgraph.png
	
	:: If build hour is greater or equal of 5:00 then behave as DAY build (do not post fps graph - no new values)
	if !timeHourCreating! GEQ 5 (
		call %SendToNG% "%branch% AUTOTEST FPS (revision %SVNrevisionNo%)" %batchDir%autotestFps.txt
	) else (
		if exist %batchDir%fpsgraph.png (
			call %SendToNG% "%branch% AUTOTEST FPS (revision %SVNrevisionNo%)" %batchDir%autotestFps.txt %batchDir%fpsgraph.png
		) else (
			call %SendToNG% "%branch% AUTOTEST FPS (revision %SVNrevisionNo%)" %batchDir%autotestFps.txt
		)
	)
	
	:: Autotest result
	call %SendToNG% "%branch% AUTOTEST complete (revision %SVNrevisionNo%)" %batchDir%autotestResult.txt
)

:noAutotest


::=============================================================================
:: Compile JNI Scripting
::=============================================================================
if [%JNIBuild%]==[1] (
	echo *** Building JNI...
	call %batchDir%JNIBuild.bat
	set JNIBuildErrorLevel=%errorlevel%
	::If JNIBuild failed and we want to send to NG just do it
	if not [%JNIBuildErrorLevel%]==[0] if [%wantSendToNG%]==[1] (
			call %SendToNG% "%branch% JNI BUILD failed" %batchDir%JNIBuildResult.txt
	)
) else (
	set JNIBuildErrorLevel=1
)
:JNIBuildOK


::=============================================================================
:: Deploying
::=============================================================================

:deploy

if [%deploy%]==[0] goto noDeploy

echo *** Deploying...

echo +++ Copy !productName! to !outputInternal!:
::robocopy %autotestDir%\Addons %outputInternal%\Addons *.* /S /E /NP
:: Using FreeFileSync for mirroring Addons from Arma3.Autotest/Addons to Arma3.Update/Addons
:: This synchronization create log files in Arma3.Backup and backup of changed and deleted data
:: Only copy when we build Internal build
if [!InternalBuildSuccessful!]==[1] (
	call !batchDir!Autotest_Update_SyncJob.bat
)

echo +++ Copy Dta to output directory \Dta...
if [!InternalBuildSuccessful!]==[1] call:funcDeployDtaDir !outputInternal! !productBinAlphaDir! !exeBackupFullPathBuildInternal!
if [!SteamBetaBuildSuccessful!]==[1] call:funcDeployDtaDir !outputSteamBetaDir! !productBinAlphaDir! !exeBackupFullPathBuildSteamBeta!
if [!SteamAlphaLiteBuildSuccessful!]==[1] call:funcDeployDtaDir !outputSteamAlphaLiteDir! !productBinAlphaLiteDir! !exeBackupFullPathBuildSteamAlphaLite!
if [!SteamDedicatedServerBuildSuccessful!]==[1] call:funcDeployDtaDir !outputSteamDedicatedServerDir! !productBinAlphaDir! !exeBackupFullPathBuildSteamDedicatedServer!

:: Copy design only into internal directory
xcopy /s !autotestDir!\Design\*.* !outputInternal!\Design\ /y

if [%JNIBuildErrorLevel%]==[0] (
	if [%InternalBuildSuccessful%]==[1] call:funcDeployJNI !outputInternal!
	if [%SteamBetaBuildSuccessful%]==[1] call:funcDeployJNI !outputSteamBetaDir!
	if [%SteamAlphaLiteBuildSuccessful%]==[1] call:funcDeployJNI !outputSteamAlphaLiteDir!
	if [%SteamDedicatedServerBuildSuccessful%]==[1] call:funcDeployJNI !outputSteamDedicatedServerDir!
)

::=============================================================================
:: Deploying .exe, .map and .pdb
::=============================================================================

if [%InternalBuildSuccessful%]==[1] call:funcDeployExeMapPdb !outputInternal! !outputBuildInternalName! !outputAppInternalName!
if [%SteamBetaBuildSuccessful%]==[1] call:funcDeployExeMapPdb !outputSteamBetaDir! !outputBuildSteamBetaName! !outputAppSteamBetaName!
if [%SteamAlphaLiteBuildSuccessful%]==[1] call:funcDeployExeMapPdb !outputSteamAlphaLiteDir! !outputBuildSteamAlphaLiteName! !outputAppSteamAlphaLiteName!
if [%SteamDedicatedServerBuildSuccessful%]==[1] call:funcDeployExeMapPdb !outputSteamDedicatedServerDir! !outputBuildSteamDedicatedServerName! !outputAppSteamDedicatedServerName!

::=============================================================================
:: Deploying *.dll and dll\*.*
::=============================================================================
echo +++ Copy *.dll and dll\ to output directory
::copy %buildDir%*.cfg %outputInternal% /y
::copy %buildDir%*.bat %outputInternal% /y
copy %buildDir%*.dll %outputInternal% /y
if [%InternalBuildSuccessful%]==[1] xcopy /y %buildDir%*.dll %outputInternal%
if [%SteamBetaBuildSuccessful%]==[1] xcopy /y %buildDir%*.dll %outputSteamBetaDir%
if [%SteamAlphaLiteBuildSuccessful%]==[1] xcopy /y %buildDir%*.dll %outputSteamAlphaLiteDir%
if [%SteamDedicatedServerBuildSuccessful%]==[1] xcopy /y %buildDir%*.dll %outputSteamDedicatedServerDir%

if [%InternalBuildSuccessful%]==[1] xcopy /y %buildDir%\dll\*.* %outputInternal%dll\
if [%SteamBetaBuildSuccessful%]==[1] xcopy /y %buildDir%\dll\*.* %outputSteamBetaDir%dll\
if [%SteamAlphaLiteBuildSuccessful%]==[1] xcopy /y %buildDir%\dll\*.* %outputSteamAlphaLiteDir%dll\
if [%SteamDedicatedServerBuildSuccessful%]==[1] xcopy /y %buildDir%\dll\*.* %outputSteamDedicatedServerDir%dll\


::=============================================================================
:: Deploying SteamBeta-Dev to WebDAV (Deploy to Steam)
::=============================================================================
set webDAVSendErrorLevel=0
if [%sendToWebDAV%]==[1] (
	del /q %batchDir%sendInfo.txt 2>nul

	if [%SteamBetaBuildSuccessful%]==[1] (
		echo +++ Curl: Send files to %webDAVSteamBetaPath%

		for %%I in ("%outputSteamBetaDir%%outputAppSteamBetaName%.*") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaPath% %%~I
		)
		for %%I in ("%outputSteamBetaDir%*.dll") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaPath% %%~I
		)
		for %%I in ("%outputSteamBetaDir%dll\*.*") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaPath% %%~I dll
		)
		for %%I in ("%outputSteamBetaDir%Dta\*.*") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaPath% %%~I Dta
		)
	)

	if [%SteamDedicatedServerBuildSuccessful%]==[1] (
		echo +++ Curl: Send files to %webDAVSteamBetaDedicatedServerPath%

		for %%I in ("%outputSteamDedicatedServerDir%%outputAppSteamDedicatedServerName%.*") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaDedicatedServerPath% %%~I
		)
		for %%I in ("%outputSteamDedicatedServerDir%*.dll") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaDedicatedServerPath% %%~I
		)
		for %%I in ("%outputSteamDedicatedServerDir%dll\*.*") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaDedicatedServerPath% %%~I dll
		)
		for %%I in ("%outputSteamDedicatedServerDir%Dta\*.*") do (
			call:funcSendFileToWebDAV %webDAVSteamBetaDedicatedServerPath% %%~I Dta
		)
	)
)
if not [%webDAVSendErrorLevel%]==[0] if [%wantSendToNG%]==[1] (
	call %SendToNG% "%branch% Send of SteamBeta to WebDAV failed. (revision %SVNrevisionNo%)" %batchDir%sendInfo.txt
)

::=============================================================================
:: Deploying svninfo and bedar_stat
::=============================================================================
echo +++ Deploy svninfo and bedar_stat
copy %batchDir%svninfo_uncensored.txt %outputInternal%\svn_info.txt /y
echo done

set lasterrorlevel=%errorlevel%

:: Backup rpt
if [%InternalBuildSuccessful%]==[1] (
	if not [%autotest%]==[0] (
		copy %autotestDir%bedar_stat.rpt %outputInternal% /y
		copy %autotestDir%bedar_stat.rpt %logsDstFullPath% /y
	)
)

if not [%lasterrorlevel%]==[0] goto deployFail

echo Deploying finished successfully

::=============================================================================
:: Sending info messages
::=============================================================================

:: Create deploy info
echo Sending info to NG
del /q %batchDir%deployInfo.txt 2>nul
echo Build %dateBuild% %timeBuild% (revision %SVNrevisionNo%) >> %batchDir%deployInfo.txt
echo. >> %batchDir%deployInfo.txt
::echo protection:%protection% >> %batchDir%deployInfo.txt

:: deploy info
if [%InternalBuildSuccessful%]==[1] (
	if [%autotestErrorLevel%]==[0] (
		echo %productName% buildInternal %branch% has been distributed.>> %batchDir%deployInfo.txt
		echo  - autotest=%autotest% >> %batchDir%deployInfo.txt
		echo. >> %batchDir%deployInfo.txt
	)
)

if [%SteamBetaBuildSuccessful%]==[1] (
	if [%autotestErrorLevel%]==[0] (
		echo %productName% buildSteamBeta %branch% has been distributed.>> %batchDir%deployInfo.txt
		echo  - autotest=%autotest% >> %batchDir%deployInfo.txt
		echo. >> %batchDir%deployInfo.txt
	)
)

if [%SteamAlphaLiteBuildSuccessful%]==[1] (
	if [%autotestErrorLevel%]==[0] (
		echo %productName% buildSteamAlphaLite %branch% has been distributed.>> %batchDir%deployInfo.txt
		echo. >> %batchDir%deployInfo.txt
	)
)

if [%SteamDedicatedServerBuildSuccessful%]==[1] (
	if [%autotestErrorLevel%]==[0] (
		echo %productName% buildSteamDedicatedServer %branch% has been distributed.>> %batchDir%deployInfo.txt
		echo. >> %batchDir%deployInfo.txt
	)
)



:: Send to NG
if [%wantSendToNG%]==[1] (
	call %SendToNG% "%branch% BUILD distributed (revision %SVNrevisionNo%)" %batchDir%deployInfo.txt
)

echo Finished successfully
:noDeploy


goto end

::=============================================================================
:: Something Failed
::=============================================================================

:svnUpdateFailed
call:funcReportError "%branch% SVN Update failed." %batchDir%svnUpdateError.txt
set criticalError=1
goto end

:buildFail
call:funcReportError "%branch% BUILD failed. (revision %SVNrevisionNo%)" %buildLog%
set criticalError=1
goto end

:generateShaderFail
call:funcReportError "%branch% Generate shaders failed. (revision %SVNrevisionNo%)" %batchDir%empty.txt
set criticalError=1
goto end

:autotestFailed
call:funcReportError "%branch% AUTOTEST failed. (revision %SVNrevisionNo%)" %batchDir%autotestResult.txt
set criticalError=1
goto end

:deployFail
call:funcReportError "%branch% Deployment failed. (revision %SVNrevisionNo%)" %batchDir%empty.txt
set criticalError=1
goto end

:protectionFailed
call:funcReportError "%branch% Protection failed." %batchDir%empty.txt
set criticalError=1
goto end

:signFailed
call:funcReportError "%branch% Sign failed." %batchDir%empty.txt
set criticalError=1
goto end


::=============================================================================
:: Functions
::=============================================================================

::-----------------------------------------------------------------------------
:: Report error to NG
:: %1 message
:: %2 error log file
:funcReportError
if [%wantSendToNG%]==[1] call %SendToNG% %1 %2
echo Finished - %1
goto:eof

::-----------------------------------------------------------------------------
:: Generate one build preset for incredibuild
:: We can't use SETLOCAL because we want to change global variables
:funcGenerateBuildPreset
set buildIBPreset=!buildIBPreset!		^<Configuration Name=%1^>!LineFeed!
set buildIBPreset=!buildIBPreset!!buildIBCfgProjectInfo!
set buildIBPreset=!buildIBPreset!!buildIBLibProjectInfo!
set buildIBPreset=!buildIBPreset!!buildIBUnitTestProjectInfo!
set buildIBPreset=!buildIBPreset!		^</Configuration^>!LineFeed!
:: Clear Cfg and UnitTest so we build it only once
set buildIBCfgProjectInfo=
set buildIBUnitTestProjectInfo=
goto:eof

::-----------------------------------------------------------------------------
:: Build one configuration
:: %1 Version of application for echo
:: %2 Build configuration
:: %3 Full path to exe backup directory
:: %4 Name of application (without .exe)
:funcBuildConfiguration
SETLOCAL
set infoName=%1
set buildCfg=%2
set exebackupFullPath=%3
set outputBuildName=%4
echo *** Building !infoName! version...
if [!buildWithIncrediBuild!]==[0] (
	!devenv! !Arma3sln! /build !buildCfg! /Out "!buildLog!"
) else (
	!incredibuild! !Arma3sln! !rebuild! /cfg=!buildCfg! /log="!buildLog!"
)
echo errorlevel %errorlevel%
if errorlevel 1 goto buildFail
echo Build of !infoName! version finished successfully

call:funcGenerateBinCfg

:: Generate shaders and export java interface
if not [!outputBuildName!]==[] (
	call:funcGenerateShaders !outputBuildName!
) else (
	:: We don't want any shaders in server configuration
  del /q /f !buildDir!bin\*.shdc 2>nul
)

call:funcCreateBinPbo !exebackupFullPath!

ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Protect file by steam
:: %1 Full path to .exe which should be protected
:: %2 Steam AppId
:funcProtectSteam
SETLOCAL
set fullPathExeName=%1
set steamAppId=%2
echo Steam protection !fullPathExeName! version...
!steamDrmTool! -remotedrm !fullPathExeName! !steamAppId! 38
echo errorlevel %errorlevel%
if errorlevel 1 goto protectionFailed
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Sign app .exe
:: %1 Name of application (without .exe)
:funcSignAppExe
SETLOCAL
set outputBuildName=%1
cmd /c call !signTool! !buildDir!!outputBuildName!.exe
if errorlevel 1 goto signFailed
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Backup executable (.exe, .map, .pdb) and rename .exe
:: %1 Name of application after build (without .exe)
:: %2 Final name of application (without .exe)
:: %3 Full path to exe backup directory
:funcBackupExeMapPdb
SETLOCAL
set outputBuildName=%1
set outputAppName=%2
set exebackupFullPath=%3
copy !buildDir!!outputBuildName!.exe !exebackupFullPath! /y
copy !buildDir!!outputBuildName!.map !exebackupFullPath! /y
copy !buildDir!!outputBuildName!.pdb !exebackupFullPath! /y

if not [!outputAppName!]==[!outputBuildName!] (
	del /q !exebackupFullPath!\!outputAppName!.exe 2>nul
	ren !exebackupFullPath!\!outputBuildName!.exe !outputAppName!.exe
)
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Do autotest mission
:: %autotestName% name of autotest
:: %lastErrorLevel% if not 0, log last rpt lines
:funcCreateAutotestInfo
if exist %debugLogPath% (
	echo. >> %batchDir%autotestInfo.txt
	echo %autotestName% info: >> %batchDir%autotestInfo.txt
	echo =============================================================================== >> %batchDir%autotestInfo.txt
	%perl% %bedarDir%deriveAutotestInfo.pl %debugLogPath% %batchDir%autotestInfo.txt
	echo. >> %batchDir%autotestInfo2.txt
	echo %autotestName% slow frames >> %batchDir%autotestInfo2.txt
	echo =============================================================================== >> %batchDir%autotestInfo2.txt
	%perl% %bedarDir%autotestresult\at-info.pl %debugLogPath% 1>> %batchDir%autotestInfo2.txt 2>&1
)
goto:eof


::-----------------------------------------------------------------------------
:: Copy crash logs
:: %1 output dir name
:funcCopyCrashLogs
set logsDir=%logsDstFullPath%\%1
md %logsDir%
echo +++ Copy logs to %logsDir%
copy %rptLogPath% %logsDir% /y
copy %debugLogPath% %logsDir% /y
copy %minidump% %logsDir% /y
goto:eof


::-----------------------------------------------------------------------------
:: Copy crash logs
:: %1 output dir name
:funcCopySteamBetaCrashLogs
set logsDir=%logsDstFullPath%\%1
md %logsDir%
echo +++ Copy logs to %logsDir%
copy %rptSteamBetaLogPath% %logsDir% /y
copy %minidumpSteamBeta% %logsDir% /y
goto:eof


::-----------------------------------------------------------------------------
:: Send one file to WebDAV directory
:: %1 full path to file
:: %2 optional subdirectory on WebDAV
:funcSendFileToWebDAV
SETLOCAL
set curlTargetPath=%1
set curlFullFileName=%2
set curlTargetSubDirectory=
if not [%3]==[] set curlTargetSubDirectory=%3/
echo Send file !curlFullFileName! to /!curlTargetSubDirectory!
echo Send file !curlFullFileName! to /!curlTargetSubDirectory! >> !batchDir!sendInfo.txt 2>&1
!curl! -u builder:SyRpTnogD45s -k -T "!curlFullFileName!" !curlTargetPath!!curlTargetSubDirectory! 1>>!batchDir!sendInfo.txt 2>NUL
ENDLOCAL
if errorlevel 1 (
	echo Error: %errorlevel%
	set webDAVSendErrorLevel=1
)
goto:eof

::-----------------------------------------------------------------------------
:: Generate shaders on given outputBuildName
:: %1 output build name
:funcGenerateShaders
SETLOCAL
set shaderExe=%1.exe
echo *** Generate shaders (!shaderExe!)
cd /d !buildDir!
del /q /f !buildDir!bin\*.shdc 2>nul
echo   ---errorlevel before generating shaders: %errorlevel%
!shaderExe! -nosplash -window -GenerateShaders -jExportInterface -noAsserts -mod=
echo   ---errorlevel after generating shaders: %errorlevel%
set shadersOK=1
if not errorlevel 1 (
	for %%I in (Bin\*.*) do (
		set file=%%~nI
		set fileSize=%%~zI
		if [!fileSize!]==[0] (
			echo !file!: file size=!fileSize!
			set shadersOK=0
		)
	)
)
::If shaders are not ok by file size, try to generate them again
if not [!shadersOK!]==[1] (
	echo   ---errorlevel before generating shaders: %errorlevel%
	!shaderExe! -nosplash -window -GenerateShaders -jExportInterface -noAsserts -mod=
	echo   ---errorlevel after generating shaders: %errorlevel%
	
	if not errorlevel 1 (
		for %%I in (Bin\*.*) do (
			set file=%%~nI
			set fileSize=%%~zI
			if [!fileSize!]==[0] (
				echo !file!: file size=!fileSize!
				set shadersOK=0
				EXIT /B 1
			)
		)
	)
)
:: If we failed then exit application
if errorlevel 1 goto generateShaderFail
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Generate bin configs
:funcGenerateBinCfg
SETLOCAL
if [!Binarize!]==[1] (
	echo *** Binarize configs...
	cd /d !buildDir!
	cd bin
	if exist config.cpp (
		b:\cfgconvert\cfgConvert -bin -dst config.bin config.cpp
	)
	del /q /f !buildDir!bin\*.?pp 2>nul
	del /q /f !buildDir!bin\*.h 2>nul
)
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Generate bin.pbo and copy into backup directory
:: %1 Full path to exe backup directory
:funcCreateBinPbo
SETLOCAL
set exebackupFullPath=%1
if [!Binarize!]==[1] (
	echo *** Create the PBO...
	del /q /f !buildDir!bin.pbo* 2>nul
	b:\filebank\filebank -exclude b:\FileBank\exclude.lst -property prefix=bin !buildDir!bin
	b:\security\dsSignFile.exe b:\security\a3demo.biprivatekey !buildDir!bin.pbo

	echo +++ Copy bin.pbo to backup directory
	copy !buildDir!bin.pbo* !exeBackupFullPath! /y
)
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Copy Dta directory into output directory
:: %1 Output directory
:: %2 Product bin directory
:: %3 Full path to exe backup directory
:funcDeployDtaDir
SETLOCAL
set outputDir=%1
set productBinDir=%2
set exebackupFullPath=%3
xcopy !autotestDir!\Dta\*.* !outputDir!\Dta\ /y
xcopy !productBinDir!product.bin !outputDir!\Dta\ /y
if [!Binarize!]==[1] xcopy !exebackupFullPath!\bin.pbo* !outputDir!\Dta /y
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Copy JNIScripting and jre dirs to output dir
:: %1 Output directory
:funcDeployJNI
SETLOCAL
set outputDir=%1
xcopy /s !autotestDir!\JNIScripting\*.* !outputDir!\JNIScripting\ /y
xcopy !autotestDir!\jre\lib\ext\JNIScripting.jar !outputDir!\jre\lib\ext\ /y
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Deploy executable (.exe, .map, .pdb) and rename all of them to final name
:: %1 Output directory
:: %2 Name of application after build (without .exe)
:: %3 Final name of application (without .exe)
:funcDeployExeMapPdb
SETLOCAL
set outputDir=%1
set outputBuildName=%2
set outputAppName=%3
if [!autotestErrorLevel!]==[0] (
	echo +++ Copy exe to !outputDir!...
	copy !buildDir!!outputBuildName!.exe !outputDir! /y
	copy !buildDir!!outputBuildName!.map !outputDir! /y
	copy !buildDir!!outputBuildName!.pdb !outputDir! /y
	
	if not [!outputAppName!]==[!outputBuildName!] (
		del /q !outputDir!!outputAppName!.exe 2>nul
		del /q !outputDir!!outputAppName!.map 2>nul
		del /q !outputDir!!outputAppName!.pdb 2>nul
		ren !outputDir!!outputBuildName!.exe !outputAppName!.exe
		ren !outputDir!!outputBuildName!.map !outputAppName!.map
		ren !outputDir!!outputBuildName!.pdb !outputAppName!.pdb
	)
)
ENDLOCAL
goto:eof

::-----------------------------------------------------------------------------
:: Sets the errorlevel and stops the batch immediately (Only use this at the end of script)!
:: %1 errorlevel to end application with
:haltProgram
call :__SetErrorLevel %1
call :__ErrorExit 2>nul
goto:eof

::-----------------------------------------------------------------------------
:: Sets the errorlevel of the appliacation
:: %1 errorlevel to end application with
:__SetErrorLevel
exit /b %1
goto :eof

::-----------------------------------------------------------------------------
:: Creates a syntax error, stops immediately (Don't use this anywhere!)
:__ErrorExit
()
goto :eof

::=============================================================================
:: End of building script
::=============================================================================
:end

::=============================================================================
:: Backup scripts
::=============================================================================
cd /d c:\Bis
set destDir=\\velryba\futura\backup
if not exist %destDir% md %destDir%
robocopy Build %destDir%\Build *.* /NP /MIR > nul
robocopy Bedar %destDir%\Bedar *.* /NP /MIR > nul
echo =====================================================================
echo SERVER BUILD FUTURA ENDED.
echo =====================================================================
if [!criticalError!]==[1] call:haltProgram %errorlevel%
ENDLOCAL
exit /B 0