@echo off
setlocal enabledelayedexpansion
title WINGI Print Agent
rem ============================================================
rem  WINGI meal print agent (standalone exe - no Python needed).
rem  Double-click ONCE on the branch PC. It registers a Scheduled
rem  Task so the agent:
rem    - keeps running after you close this window,
rem    - starts automatically at every logon / reboot,
rem    - pulls the latest agent from the server each time it starts.
rem ============================================================
set "DIR=%~dp0"
set "AGENT=%DIR%wingi-agent.exe"
set "CFG=%DIR%wingi-agent.json"
set "VBS=%DIR%run-hidden.vbs"
set "AGENT_URL=https://wingi.ahmedfahd.com/download/wingi-agent.exe"
set "TASK=WINGI Print Agent"

if /i "%~1"=="run" goto :run

rem ===================== SETUP (double-click) =====================
echo.
echo  WINGI Print Agent - setup
echo  Downloading agent (no Python needed)... please wait ~20s
call :download
if not exist "%AGENT%" (
  echo.
  echo  ERROR: could not download the agent. Check internet and retry.
  echo.
  pause
  exit /b
)

if not exist "%CFG%" (
  echo.
  echo  === One-time login: this branch's CASHIER account ===
  set /p "AUSER=Cashier username: "
  set /p "APASS=Cashier password: "
  > "%CFG%" echo {"username":"!AUSER!","password":"!APASS!"}
  echo  Saved.
)

rem hidden restart-loop launcher (runs the agent, restarts it if it stops)
> "%VBS%" echo CreateObject("WScript.Shell").Run "cmd /c ""%DIR%run-agent.bat"" run", 0, False

rem remove any old auto-start shortcut from a previous install
del "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\WINGI Print Agent.lnk" >nul 2>nul

rem register as a Scheduled Task at logon (owned by Task Scheduler -> survives
rem closing this window and starts on every boot)
schtasks /create /f /sc onlogon /tn "%TASK%" /tr "wscript.exe //B \"%VBS%\"" >nul 2>nul

rem stop any running copy, then start it NOW via the task (fully detached)
taskkill /f /im wingi-agent.exe >nul 2>nul
schtasks /run /tn "%TASK%" >nul 2>nul
if errorlevel 1 (
  rem fallback if Task Scheduler is unavailable: Startup shortcut + launch now
  powershell -NoProfile -Command "$s=(New-Object -ComObject WScript.Shell).CreateShortcut([Environment]::GetFolderPath('Startup')+'\WINGI Print Agent.lnk');$s.TargetPath='%VBS%';$s.Save()" >nul 2>nul
  start "" wscript //B "%VBS%"
)

echo.
echo  ============================================
echo   Print agent is running in the background.
echo   It KEEPS running after you close this window,
echo   and starts automatically when the PC boots.
echo   You can close this window now.
echo  ============================================
echo.
timeout /t 6 >nul
exit /b

rem ===================== RUN (hidden background) =====================
:run
:loop
call :download
"%AGENT%"
timeout /t 5 >nul
goto loop

rem ---- download latest exe (fast: progress bar off; TLS 1.2; keep old on fail) ----
:download
powershell -NoProfile -Command "$ProgressPreference='SilentlyContinue'; try{ [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12 }catch{}; try{ Invoke-WebRequest -UseBasicParsing '%AGENT_URL%' -OutFile '%AGENT%.new'; Move-Item -Force '%AGENT%.new' '%AGENT%' }catch{}" >nul 2>nul
exit /b
