@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "BASE=%~dp0"
if "%BASE:~-1%"=="\" set "BASE=%BASE:~0,-1%"

set "LOG_DIR=%BASE%\logs"
set "SERVICE_NAME=cli-proxy-api"
set "NSSM=%BASE%\nssm.exe"
set "APP_EXE=%BASE%\cli-proxy-api.exe"
set "CONFIG_FILE=%BASE%\config.yaml"
set "INSTALL_LOG=%LOG_DIR%\install.log"

if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

call :log "========== 开始安装/配置服务 =========="
call :log "BASE=%BASE%"
call :log "SERVICE_NAME=%SERVICE_NAME%"
call :log "NSSM=%NSSM%"

if not exist "%NSSM%" (
    call :log "错误: 找不到 nssm.exe，路径=%NSSM%"
    pause
    exit /b 1
)

if not exist "%APP_EXE%" (
    call :log "错误: 找不到程序 %APP_EXE%"
    pause
    exit /b 1
)

if not exist "%CONFIG_FILE%" (
    call :log "错误: 找不到配置文件 %CONFIG_FILE%"
    pause
    exit /b 1
)

sc query "%SERVICE_NAME%" >nul 2>&1
set "SC_ERR=%errorlevel%"
call :log "sc query 返回码=%SC_ERR%"

if "%SC_ERR%"=="0" (
    call :log "检测到服务已存在，准备替换"

    call :log "尝试停止旧服务"
    "%NSSM%" stop "%SERVICE_NAME%" >> "%INSTALL_LOG%" 2>&1

    call :log "删除旧服务"
    "%NSSM%" remove "%SERVICE_NAME%" confirm >> "%INSTALL_LOG%" 2>&1
    if errorlevel 1 (
        call :log "错误: 删除旧服务失败"
        pause
        exit /b 1
    )

    timeout /t 2 /nobreak >nul
) else if "%SC_ERR%"=="1060" (
    call :log "服务不存在，执行全新安装"
) else (
    call :log "错误: sc query 检测服务状态失败，返回码=%SC_ERR%"
    pause
    exit /b 1
)

call :log "安装服务"
"%NSSM%" install "%SERVICE_NAME%" "%APP_EXE%" >> "%INSTALL_LOG%" 2>&1
if errorlevel 1 (
    call :log "错误: 安装服务失败"
    pause
    exit /b 1
)

call :log "设置工作目录"
"%NSSM%" set "%SERVICE_NAME%" AppDirectory "%BASE%" >> "%INSTALL_LOG%" 2>&1
if errorlevel 1 (
    call :log "错误: 设置工作目录失败"
    pause
    exit /b 1
)

call :log "设置启动参数"
"%NSSM%" set "%SERVICE_NAME%" AppParameters "-config ""%CONFIG_FILE%""" >> "%INSTALL_LOG%" 2>&1
if errorlevel 1 (
    call :log "错误: 设置启动参数失败"
    pause
    exit /b 1
)

call :log "设置标准输出日志"
"%NSSM%" set "%SERVICE_NAME%" AppStdout "%LOG_DIR%\out.log" >> "%INSTALL_LOG%" 2>&1
if errorlevel 1 (
    call :log "错误: 设置标准输出日志失败"
    pause
    exit /b 1
)

call :log "设置错误输出日志"
"%NSSM%" set "%SERVICE_NAME%" AppStderr "%LOG_DIR%\err.log" >> "%INSTALL_LOG%" 2>&1
if errorlevel 1 (
    call :log "错误: 设置错误输出日志失败"
    pause
    exit /b 1
)

call :log "设置开机自动启动"
"%NSSM%" set "%SERVICE_NAME%" Start SERVICE_AUTO_START >> "%INSTALL_LOG%" 2>&1
if errorlevel 1 (
    call :log "错误: 设置开机自动启动失败"
    pause
    exit /b 1
)

call :log "启动服务"
"%NSSM%" start "%SERVICE_NAME%" >> "%INSTALL_LOG%" 2>&1
if errorlevel 1 (
    call :log "错误: 启动服务命令执行失败"
    pause
    exit /b 1
)

call :log "========== 服务安装/配置完成 =========="
pause
exit /b 0

:log
echo [%date% %time%] %~1
>> "%INSTALL_LOG%" echo [%date% %time%] %~1
exit /b 0