@echo off
setlocal EnableDelayedExpansion

set "AppName=cmvr-iot-admin.jar"
set "AppJar=cmvr-iot-admin\target\cmvr-iot-admin.jar"
if exist "%AppName%" set "AppJar=%AppName%"
set "JVM_OPTS=-Dname=%AppName% -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -XX:+UseParallelGC"

if not exist "%AppJar%" (
    echo Missing %AppJar%. Run mvn clean package -DskipTests first.
    exit /b 1
)

echo.
echo [1] Start %AppName%
echo [2] Stop %AppName%
echo [3] Restart %AppName%
echo [4] Status %AppName%
echo [5] Exit
echo.
set /p ID=Select an action: 
if "%ID%"=="1" goto start
if "%ID%"=="2" goto stop
if "%ID%"=="3" goto restart
if "%ID%"=="4" goto status
if "%ID%"=="5" exit /b 0
exit /b 1

:findPid
set "pid="
for /f "tokens=1" %%a in ('jps -lv ^| findstr /C:"%AppName%"') do set "pid=%%a"
exit /b 0

:start
call :findPid
if defined pid (
    echo %AppName% is already running with PID !pid!.
    exit /b 0
)
start "cmvr-iot" javaw %JVM_OPTS% -jar "%AppJar%"
echo Started %AppName%.
exit /b 0

:stop
call :findPid
if not defined pid (
    echo %AppName% is not running.
    exit /b 0
)
taskkill /f /pid !pid!
exit /b %ERRORLEVEL%

:restart
call :stop
call :start
exit /b 0

:status
call :findPid
if defined pid (echo %AppName% is running with PID !pid!.) else (echo %AppName% is not running.)
exit /b 0
