@echo off
setlocal EnableExtensions EnableDelayedExpansion

if /i not "%OS%"=="Windows_NT" (
  echo Siraya Printer Sync requires Windows.
  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 - Update
echo ===========================================
echo.

set ERR=0

if exist "%~dp0Sync.exe" (
  "%~dp0Sync.exe" apply --channel stable
  set ERR=!errorlevel!
) else (
  echo Sync.exe not found — using Node sync fallback...
  set "NODE_EXE=%ProgramFiles%\Siraya\Printer\runtime\node.exe"
  set "SYNC_JS=%~dp0sync-apply.js"
  if not exist "!NODE_EXE!" (
    echo Printer not installed. Run Install.cmd first.
    pause
    exit /b 1
  )
  if not exist "!SYNC_JS!" set "SYNC_JS=%ProgramFiles%\Siraya\Printer\installer\windows\sync-apply.js"
  if not exist "!SYNC_JS!" (
    echo sync-apply.js not found.
    pause
    exit /b 1
  )
  "!NODE_EXE!" "!SYNC_JS!" apply --channel stable
  set ERR=!errorlevel!
)

if !ERR! neq 0 (
  echo.
  echo Update failed. Logs: %ProgramData%\Siraya\Printer\logs\
  pause
  exit /b !ERR!
)

echo.
echo Update complete.
pause
exit /b 0
