@echo off
setlocal
cd /d "%~dp0"
"%~dp0ForceFeedback Test Circuit.exe" --fanatec %*
set "clientExitCode=%errorlevel%"
if "%clientExitCode%"=="42" goto waitForUpdate
if not "%clientExitCode%"=="0" pause
exit /b %clientExitCode%

:waitForUpdate
echo Waiting for the client update to finish.
timeout /t 2 /nobreak > nul
set "updateLock=%TEMP%\ForceFeedback Test Circuit\client-update.lock"
set /a updateWaitCount=0
:updateWaitLoop
if not exist "%updateLock%" goto restartAfterUpdate
set "updatePid="
set /p updatePid=<"%updateLock%"
if not defined updatePid goto restartAfterUpdate
powershell.exe -NoLogo -NoProfile -NonInteractive -Command "if (Get-Process -Id %updatePid% -ErrorAction SilentlyContinue) { exit 0 } else { exit 1 }" > nul 2>&1
if errorlevel 1 goto restartAfterUpdate
set /a updateWaitCount+=1
if %updateWaitCount% GEQ 120 goto restartAfterUpdate
echo Update wait %updateWaitCount%/120
timeout /t 1 /nobreak > nul
goto updateWaitLoop

:restartAfterUpdate
echo Restarting the client.
"%~dp0ForceFeedback Test Circuit.exe" --fanatec --skip-update %*
set "clientExitCode=%errorlevel%"
if not "%clientExitCode%"=="0" pause
exit /b %clientExitCode%
