@echo off
REM ============================================================================
REM  Install nginx as Windows Service using NSSM
REM ============================================================================
setlocal EnableDelayedExpansion

set "NGINX_DIR=%~dp0"
set "SERVICE_NAME=nginx"

REM Remove trailing backslash for some commands
set "NGINX_DIR_NOSLASH=%NGINX_DIR:~0,-1%"

REM Check for admin rights
net session >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
    echo ERROR: This script requires administrator privileges.
    echo Please run as Administrator.
    pause
    exit /b 1
)

REM Check for NSSM
if exist "%NGINX_DIR%nssm.exe" (
    set "NSSM=%NGINX_DIR%nssm.exe"
) else (
    where nssm >nul 2>&1
    if %ERRORLEVEL% NEQ 0 (
        echo ERROR: NSSM not found. Place nssm.exe in this directory.
        pause
        exit /b 1
    )
    set "NSSM=nssm"
)

echo Installing nginx as Windows Service...
echo   Directory: %NGINX_DIR%
echo.

REM Stop any existing nginx processes first
taskkill /F /IM nginx.exe >nul 2>&1

REM Install service with -p prefix parameter
"%NSSM%" install %SERVICE_NAME% "%NGINX_DIR%nginx.exe"
"%NSSM%" set %SERVICE_NAME% AppDirectory "%NGINX_DIR_NOSLASH%"
"%NSSM%" set %SERVICE_NAME% AppParameters "-p %NGINX_DIR_NOSLASH%"
"%NSSM%" set %SERVICE_NAME% AppEnvironmentExtra "OPENSSL_CONF=%NGINX_DIR%openssl.cnf" "OPENSSL_MODULES=%NGINX_DIR%ossl-modules"
"%NSSM%" set %SERVICE_NAME% DisplayName "nginx FIPS"
"%NSSM%" set %SERVICE_NAME% Description "nginx web server with OpenSSL FIPS"
"%NSSM%" set %SERVICE_NAME% Start SERVICE_AUTO_START

REM Configure proper shutdown - kill entire process tree
"%NSSM%" set %SERVICE_NAME% AppStopMethodSkip 0
"%NSSM%" set %SERVICE_NAME% AppStopMethodConsole 1000
"%NSSM%" set %SERVICE_NAME% AppStopMethodWindow 1000
"%NSSM%" set %SERVICE_NAME% AppStopMethodThreads 1000
"%NSSM%" set %SERVICE_NAME% AppKill 1
"%NSSM%" set %SERVICE_NAME% AppExit Default Restart

echo.
echo Service installed successfully
echo.
echo Starting service...
"%NSSM%" start %SERVICE_NAME%
echo.
echo Commands:
echo   nssm start nginx   - Start service
echo   nssm stop nginx    - Stop service
echo   nssm restart nginx - Restart service
echo   nssm status nginx  - Check status
echo   nssm edit nginx    - Edit service config
echo   nssm remove nginx  - Remove service
echo.
endlocal
