@echo off
REM XBC Remote Controller - Service Installer
REM This script installs the server as a Windows service with auto-start

setlocal enabledelayedexpansion

REM Check for administrator privileges
net session >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
    echo.
    echo ERROR: This script requires administrator privileges.
    echo Please right-click and select "Run as administrator"
    echo.
    pause
    exit /b 1
)

cd /d "%~dp0"

REM Service configuration
set "SERVICE_NAME=XSplit Remote Server"
set "EXECUTABLE=xbc-remote-server.exe"
set "NSSM_EXE=nssm.exe"
set "NSSM_URL=http://cdn.bachmann.xyz/xbc-remote/nssm.zip"
set "NSSM_ZIP=nssm.zip"

REM Check if executable exists
if not exist "%EXECUTABLE%" (
    echo.
    echo ERROR: %EXECUTABLE% not found in current directory.
    echo Current directory: %CD%
    echo.
    pause
    exit /b 1
)

echo.
echo ========================================
echo XSplit Remote Server - Service Installer
echo ========================================
echo.

REM Check if NSSM exists, download if not
if not exist "%NSSM_EXE%" (
    echo NSSM not found. Downloading NSSM...
    echo.
    
    REM Download and extract NSSM using PowerShell
    powershell -NoProfile -ExecutionPolicy Bypass -Command "& {[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $ProgressPreference = 'SilentlyContinue'; try { Invoke-WebRequest -Uri '%NSSM_URL%' -OutFile '%NSSM_ZIP%' -ErrorAction Stop; if (Test-Path '%NSSM_ZIP%') { Expand-Archive -Path '%NSSM_ZIP%' -DestinationPath 'nssm_temp' -Force -ErrorAction Stop; $nssmPath = $null; if (Test-Path 'nssm_temp\%NSSM_EXE%') { $nssmPath = 'nssm_temp\%NSSM_EXE%' } elseif (Test-Path 'nssm_temp\win64\%NSSM_EXE%') { $nssmPath = 'nssm_temp\win64\%NSSM_EXE%' }; if ($nssmPath) { Copy-Item -Path $nssmPath -Destination '%NSSM_EXE%' -Force; Write-Host 'NSSM downloaded and extracted successfully.' -ForegroundColor Green } else { throw 'Could not find nssm.exe' }; if (Test-Path '%NSSM_ZIP%') { Remove-Item '%NSSM_ZIP%' -Force }; if (Test-Path 'nssm_temp') { Remove-Item 'nssm_temp' -Recurse -Force } } else { throw 'Download failed' } } catch { Write-Host 'ERROR: Failed to download or extract NSSM.' -ForegroundColor Red; Write-Host $_.Exception.Message -ForegroundColor Red; exit 1 } }"
    
    if %ERRORLEVEL% NEQ 0 (
        echo.
        echo ERROR: Failed to download NSSM.
        echo Please download NSSM manually from:
        echo http://cdn.bachmann.xyz/xbc-remote/nssm.zip
        echo Extract nssm.exe to this directory: %CD%
        echo.
        pause
        exit /b 1
    )
    
    if not exist "%NSSM_EXE%" (
        echo.
        echo ERROR: NSSM extraction failed.
        echo Please download NSSM manually from:
        echo http://cdn.bachmann.xyz/xbc-remote/nssm.zip
        echo Extract nssm.exe to this directory: %CD%
        echo.
        pause
        exit /b 1
    )
    
    echo.
)

REM Check if service already exists
"%NSSM_EXE%" status "%SERVICE_NAME%" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    echo Service "%SERVICE_NAME%" already exists.
    echo.
    set /p OVERWRITE="Do you want to remove and reinstall it? [Y/N]: "
    if /i not "!OVERWRITE!"=="Y" (
        echo Installation cancelled.
        echo.
        pause
        exit /b 0
    )
    
    echo.
    echo Removing existing service...
    "%NSSM_EXE%" stop "%SERVICE_NAME%" >nul 2>&1
    "%NSSM_EXE%" remove "%SERVICE_NAME%" confirm >nul 2>&1
    timeout /t 2 >nul
    echo.
)

REM Get full path to executable
set "EXECUTABLE_PATH=%CD%\%EXECUTABLE%"

echo Installing service "%SERVICE_NAME%"...
echo Executable: %EXECUTABLE_PATH%
echo.

REM Install the service
"%NSSM_EXE%" install "%SERVICE_NAME%" "%EXECUTABLE_PATH%"

if %ERRORLEVEL% NEQ 0 (
    echo.
    echo ERROR: Failed to install service.
    echo.
    pause
    exit /b 1
)

REM Set service display name
"%NSSM_EXE%" set "%SERVICE_NAME%" DisplayName "%SERVICE_NAME%" >nul 2>&1

REM Set service description
"%NSSM_EXE%" set "%SERVICE_NAME%" Description "Relay server for XBC Remote Controller" >nul 2>&1

REM Set start type to automatic
"%NSSM_EXE%" set "%SERVICE_NAME%" Start SERVICE_AUTO_START >nul 2>&1

REM Set working directory
"%NSSM_EXE%" set "%SERVICE_NAME%" AppDirectory "%CD%" >nul 2>&1

echo.
echo Service installed successfully!
echo.

REM Start the service
echo Starting service...
"%NSSM_EXE%" start "%SERVICE_NAME%" >nul 2>&1

REM Wait before checking if service is actually running (to avoid seeing initial error messages)
timeout /t 3 /nobreak >nul
set "SERVICE_STARTED=0"
set "RETRY_COUNT=0"

:CHECK_SERVICE
sc query "%SERVICE_NAME%" | find "RUNNING" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    set "SERVICE_STARTED=1"
    goto :SERVICE_CHECK_DONE
)

set /a RETRY_COUNT+=1
if %RETRY_COUNT% LSS 5 (
    timeout /t 1 /nobreak >nul
    goto :CHECK_SERVICE
)

:SERVICE_CHECK_DONE
if !SERVICE_STARTED! EQU 1 (
    echo.
    echo Service started successfully!
    echo.
    echo The service "%SERVICE_NAME%" is now running and will start automatically on boot.
) else (
    echo.
    echo WARNING: Service start command was sent, but service may still be starting.
    echo The service should start automatically. You can check status with: sc query "%SERVICE_NAME%"
    echo Or start it manually using: net start "%SERVICE_NAME%"
    echo.
)

echo.
echo ========================================
echo Installation complete!
echo ========================================
echo.
pause
