@echo off
setlocal enabledelayedexpansion

rem ============================================================
rem  Simple installer for SpawnSess service using NSSM
rem  Assumes this .bat, launcher.exe, monitor.exe, and nssm.exe
rem  are all in the same folder.
rem ============================================================

set SVC_NAME=AppMonitorLauncher
set SVC_DISPLAY=AppMonitorLauncher
set LOG_FILE=launcher.log

rem Get absolute path of the current folder
set "CURR_DIR=%~dp0"
set "CURR_DIR=%CURR_DIR:~0,-1%"

echo Installing service "%SVC_NAME%" from "%CURR_DIR%"

cd /d "%CURR_DIR%"

rem Install service: launcher.exe monitor.exe (relative)
.\nssm.exe install %SVC_NAME% "%CURR_DIR%\launcher.exe" "monitor.exe"

rem Working directory (so relative monitor.exe resolves correctly)
.\nssm.exe set %SVC_NAME% AppDirectory "%CURR_DIR%"

rem Redirect stdout/stderr to launcher.log (append mode)
.\nssm.exe set %SVC_NAME% AppStdout "%CURR_DIR%\%LOG_FILE%"
.\nssm.exe set %SVC_NAME% AppStderr "%CURR_DIR%\%LOG_FILE%"
.\nssm.exe set %SVC_NAME% AppStdoutCreationDisposition 4
.\nssm.exe set %SVC_NAME% AppStderrCreationDisposition 4

rem Run as LocalSystem (required for CreateProcessAsUser privileges)
.\nssm.exe set %SVC_NAME% ObjectName LocalSystem

rem Auto-restart on crash
.\nssm.exe set %SVC_NAME% AppRestartDelay 5000

rem Optional description
.\nssm.exe set %SVC_NAME% Description "Launches and monitors monitor.exe in Session 1; restarts it if it exits."

rem Display name
.\nssm.exe set %SVC_NAME% DisplayName "%SVC_DISPLAY%"

rem Start automatically
.\nssm.exe set %SVC_NAME% Start SERVICE_AUTO_START

echo.
echo Starting service...
.\nssm.exe start %SVC_NAME%

if %errorlevel%==0 (
    echo Service "%SVC_NAME%" installed and started successfully.
) else (
    echo Failed to start service "%SVC_NAME%". Check permissions or log output.
)

echo.
echo Log will be written to: %CURR_DIR%\%LOG_FILE%
echo Done.
pause
endlocal
