@echo off
REM XBC Remote Controller - Service Uninstaller
REM This script removes the server from Windows services

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 "NSSM_EXE=nssm.exe"

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

REM Check if NSSM exists
if not exist "%NSSM_EXE%" (
    echo WARNING: %NSSM_EXE% not found.
    echo Attempting to use Windows service commands instead...
    echo.
    
    REM Check if service exists using sc command
    sc query "%SERVICE_NAME%" >nul 2>&1
    if %ERRORLEVEL% NEQ 0 (
        echo Service "%SERVICE_NAME%" is not installed.
        echo.
        pause
        exit /b 0
    )
    
    REM Stop the service
    echo Stopping service...
    net stop "%SERVICE_NAME%" >nul 2>&1
    if %ERRORLEVEL% EQU 0 (
        echo Service stopped.
    ) else (
        echo Service may already be stopped or failed to stop.
    )
    echo.
    
    REM Remove the service
    echo Removing service...
    sc delete "%SERVICE_NAME%"
    
    if %ERRORLEVEL% EQU 0 (
        echo.
        echo Service removed successfully!
        echo.
        echo ========================================
        echo Uninstallation complete!
        echo ========================================
        echo.
    ) else (
        echo.
        echo ERROR: Failed to remove service.
        echo.
        pause
        exit /b 1
    )
    
    pause
    exit /b 0
)

REM Check if service exists
"%NSSM_EXE%" status "%SERVICE_NAME%" >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
    echo Service "%SERVICE_NAME%" is not installed.
    echo.
    pause
    exit /b 0
)

REM Stop the service
echo Stopping service...
"%NSSM_EXE%" stop "%SERVICE_NAME%"

if %ERRORLEVEL% EQU 0 (
    echo Service stopped successfully.
) else (
    echo Service may already be stopped or failed to stop.
)
echo.

REM Remove the service
echo Removing service...
"%NSSM_EXE%" remove "%SERVICE_NAME%" confirm

if %ERRORLEVEL% EQU 0 (
    echo.
    echo Service removed successfully!
    echo.
    echo ========================================
    echo Uninstallation complete!
    echo ========================================
) else (
    echo.
    echo ERROR: Failed to remove service.
    echo You may need to remove it manually using:
    echo   sc delete "%SERVICE_NAME%"
    echo.
    pause
    exit /b 1
)

echo.
pause
