@echo off
rem EMO on Windows: runs the server and restarts it if it stops (the Windows twin of the Mac launchd agent).
rem The scheduled task starts this hidden (conhost --headless), so there is no window to close by mistake.
rem ping is the pause because timeout needs a real console.
rem The data folder is EMO_HOME (default %USERPROFILE%\EMO); the log lives in its logs\ folder, not in the code folder.
cd /d "%~dp0.."
if "%EMO_HOME%"=="" set "EMO_HOME=%USERPROFILE%\EMO"
if not exist "%EMO_HOME%\logs" mkdir "%EMO_HOME%\logs"
set "LOG=%EMO_HOME%\logs\emo.log"
:loop
rem 10-27: the log file is locked by this redirect while node runs, so it can only be rotated here, between runs.
rem Past 20MB it moves to the archive with a time stamp (tools/cleanup.mjs handles the other logs).
for %%A in ("%LOG%") do if %%~zA GTR 20000000 (
  if not exist "%EMO_HOME%\archive\logs" mkdir "%EMO_HOME%\archive\logs"
  for /f %%i in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd-HHmm"') do move /y "%LOG%" "%EMO_HOME%\archive\logs\emo.%%i.log" >nul
)
node server.mjs >> "%LOG%" 2>&1
ping -n 11 127.0.0.1 >nul
goto loop
