@echo off
REM khaosd-ctl.bat — Control the Khaos Machine daemon on Windows
REM Usage: khaosd-ctl start | stop | restart | status

setlocal

set "KHAOSD=khaosd.exe"
set "CMD=%~1"

if "%CMD%"=="" goto usage

if /i "%CMD%"=="start" goto start
if /i "%CMD%"=="stop" goto stop
if /i "%CMD%"=="restart" goto restart
if /i "%CMD%"=="status" goto status
goto usage

:start
echo Starting %KHAOSD%...
tasklist /FI "IMAGENAME eq %KHAOSD%" 2>NUL | find /I "%KHAOSD%" >NUL
if %ERRORLEVEL%==0 (
    echo %KHAOSD% is already running.
    exit /b 0
)
start "" /b "%~dp0%KHAOSD%"
echo %KHAOSD% started.
exit /b 0

:stop
echo Stopping %KHAOSD%...
tasklist /FI "IMAGENAME eq %KHAOSD%" 2>NUL | find /I "%KHAOSD%" >NUL
if %ERRORLEVEL% NEQ 0 (
    echo %KHAOSD% is not running.
    exit /b 0
)
taskkill /IM %KHAOSD% >NUL 2>&1
if %ERRORLEVEL%==0 (
    echo %KHAOSD% stopped.
) else (
    echo Graceful stop failed, forcing...
    taskkill /F /IM %KHAOSD% >NUL 2>&1
)
exit /b 0

:restart
call :stop
timeout /t 2 /nobreak >NUL
call :start
exit /b 0

:status
tasklist /FI "IMAGENAME eq %KHAOSD%" 2>NUL | find /I "%KHAOSD%" >NUL
if %ERRORLEVEL%==0 (
    echo %KHAOSD% is running.
) else (
    echo %KHAOSD% is not running.
)
exit /b 0

:usage
echo Usage: %~n0 start ^| stop ^| restart ^| status
exit /b 1
