@echo off
chcp 65001 >nul
setlocal EnableExtensions

set "ONE_UPDATE_NO_PAUSE="
for %%A in (%*) do if /i "%%~A"=="--quiet" set "ONE_UPDATE_NO_PAUSE=1"

set "ONE_UPDATER_HELPER=%~dp0Engine\Updater\OneUpdater.exe"
if not exist "%ONE_UPDATER_HELPER%" set "ONE_UPDATER_HELPER=%~dp0Updater\OneUpdater.exe"
if not exist "%ONE_UPDATER_HELPER%" set "ONE_UPDATER_HELPER=%~dp0Updater\bin\Release\net8.0\win-x64\OneUpdater.exe"

set "ONE_UPDATER_RESULT=%TEMP%\one-updater-%RANDOM%-%RANDOM%.exit"

if exist "%ONE_UPDATER_HELPER%" (
  "%ONE_UPDATER_HELPER%" --root "%~dp0." %*
  set "ONE_UPDATE_EXIT=%ERRORLEVEL%"
  goto wait_for_temp
)

if exist "%~dp0Updater\OneUpdater.csproj" (
  dotnet run --project "%~dp0Updater\OneUpdater.csproj" -c Release -- --root "%~dp0." %*
  set "ONE_UPDATE_EXIT=%ERRORLEVEL%"
  goto wait_for_temp
)

echo OneUpdater not found: "%ONE_UPDATER_HELPER%"
set "ONE_UPDATE_EXIT=90"
goto done

:wait_for_temp
if "%ONE_UPDATE_EXIT%"=="100" (
  powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$path=$env:ONE_UPDATER_RESULT; $deadline=(Get-Date).AddMinutes(10); while((Get-Date) -lt $deadline -and !(Test-Path -LiteralPath $path)){ Start-Sleep -Milliseconds 200 }; if(Test-Path -LiteralPath $path){ $code=[int]((Get-Content -LiteralPath $path -Raw).Trim()); Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue; exit $code }; exit 12"
  set "ONE_UPDATE_EXIT=%ERRORLEVEL%"
)

:done
echo.
if not "%ONE_UPDATE_NO_PAUSE%"=="1" pause
exit /b %ONE_UPDATE_EXIT%
