@echo off
setlocal EnableExtensions

if /i not "%OS%"=="Windows_NT" (
  echo Siraya Printer Service requires Windows.
  echo On Linux or macOS, run install.sh from this folder.
  pause
  exit /b 1
)

net session >nul 2>&1
if %errorlevel% neq 0 (
  echo Requesting administrator privileges...
  powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
  exit /b
)

cd /d "%~dp0"
echo ===========================================
echo   Siraya Printer Service - Install
echo ===========================================
echo.

if exist "%~dp0stop-agent.ps1" (
  echo Stopping any existing print agent...
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-agent.ps1"
) else if exist "%~dp0installer\windows\stop-agent.ps1" (
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0installer\windows\stop-agent.ps1"
)

REM Use %~dp0. (not %~dp0) so the path has no trailing backslash before the closing quote.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install-from-folder.ps1" -BundleRoot "%~dp0." -NoBrowser
set ERR=%errorlevel%

call :check_health
if %ERR% equ 0 if %errorlevel% equ 0 goto :success

echo.
echo Install did not confirm health on port 5000 — running automatic repair...
set ATTEMPT=0

:repair_loop
set /a ATTEMPT+=1
if %ATTEMPT% gtr 3 goto :fail

echo Repair attempt %ATTEMPT% of 3...

if exist "%~dp0stop-agent.ps1" (
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-agent.ps1"
) else if exist "%~dp0installer\windows\stop-agent.ps1" (
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0installer\windows\stop-agent.ps1"
)

powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install-repair-cycle.ps1"
if %errorlevel% neq 0 (
  echo WARN: Repair cycle script returned %errorlevel%
)

timeout /t 8 /nobreak >nul
call :check_health
if %errorlevel% equ 0 goto :success
goto :repair_loop

:check_health
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { $r=Invoke-WebRequest -Uri 'http://127.0.0.1:5000/health' -UseBasicParsing -TimeoutSec 5; if($r.StatusCode -eq 200){ exit 0 } else { exit 1 } } catch { exit 1 }"
exit /b

:success
echo.
echo ===========================================
echo   INSTALL OK - http://127.0.0.1:5000
echo ===========================================
start "" "http://127.0.0.1:5000"
pause
exit /b 0

:fail
echo.
echo Installation failed. The print agent did not respond on http://127.0.0.1:5000
echo See %TEMP%\SirayaPrinter-Install.log
echo Service log: %ProgramData%\Siraya\Printer\logs\error.log
echo Try rebooting this PC, then run Install.cmd again.
pause
exit /b 1
