@echo off
REM fleet-recover.cmd - restore the Hermes dashboard on a Windows fleet machine.
REM Run in an elevated (Administrator) command prompt:
REM   curl -s https://<hub>/fleet-recover.cmd -o %TEMP%\fleet-recover.cmd
REM   %TEMP%\fleet-recover.cmd
REM
REM What it does:
REM   1. Kill the dashboard process listening on 9119 (the deployment session
REM      token provider registers at process start, so a restart is what makes
REM      a newly written .env token take effect).
REM   2. Relaunch `hermes dashboard --host 0.0.0.0 --port 9119 --no-open`
REM      detached, with the same HERMES_HOME the dashboard uses.
REM
REM The scheduled task Hermes_Gateway owns the *gateway*, not the dashboard, so
REM killing the dashboard does NOT bring it back on its own - hence this script.

setlocal enabledelayedexpansion

set "HERMES_HOME=%LOCALAPPDATA%\hermes"
if "%HERMES_HOME%"=="" set "HERMES_HOME=C:\Users\%USERNAME%\AppData\Local\hermes"

set "LOG=%HERMES_HOME%\logs\fleet-recover.out.txt"
if not exist "%HERMES_HOME%\logs" mkdir "%HERMES_HOME%\logs"

echo == fleet-recover start %date% %time% > "%LOG%"
echo HERMES_HOME=%HERMES_HOME% >> "%LOG%"

REM --- 1. find and stop the dashboard on 9119 -------------------------------
for /f "tokens=2 delims=," %%p in ('wmic process where "name='python.exe' and commandline like '%%9119%%'" get processid^,commandline /format:csv 2^>nul ^| find "9119"') do (
  echo killing dashboard: %%p >> "%LOG%"
)
wmic process where "commandline like '%%dashboard%%9119%%'" delete >nul 2>&1
timeout /t 3 /nobreak >nul

REM --- 2. relaunch the dashboard --------------------------------------------
set "HERMES_EXE=%HERMES_HOME%\hermes-agent\.hermes\bin\hermes.exe"
if not exist "%HERMES_EXE%" set "HERMES_EXE=%HERMES_HOME%\bin\hermes.exe"
if not exist "%HERMES_EXE%" (
  echo !! hermes.exe not found under %HERMES_HOME% >> "%LOG%"
  echo !! fleet-recover failed: hermes.exe not found >> "%LOG%"
  type "%LOG%"
  exit /b 4
)
echo launching %HERMES_EXE% >> "%LOG%"
start "" /b "%HERMES_EXE%" dashboard --host 0.0.0.0 --port 9119 --no-open --skip-build >> "%LOG%" 2>&1

timeout /t 8 /nobreak >nul

REM --- 3. verify ------------------------------------------------------------
set FOUND=0
for /f "tokens=5" %%p in ('netstat -ano ^| findstr ":9119" ^| findstr "LISTENING"') do set FOUND=1
if "%FOUND%"=="1" (
  echo == OK: 9119 is listening >> "%LOG%"
  type "%LOG%"
  exit /b 0
)
echo !! 9119 not listening after relaunch >> "%LOG%"
type "%LOG%"
exit /b 5
