@echo off
setlocal enabledelayedexpansion
title GTPS Node - 1-Click Game Connector
echo ========================================================
echo         GTPS Node - Windows Automatic Setup
echo ========================================================
echo.

net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [!] Requesting administrator permissions to configure hosts...
    powershell -Command "Start-Process cmd.exe -ArgumentList '/c ""%~f0""' -Verb RunAs"
    exit /b
)

set "HOSTS_FILE=%WINDIR%\System32\drivers\etc\hosts"
set "BACKUP_FILE=%WINDIR%\System32\drivers\etc\hosts.gtpsnode_backup"
set "CERT_FILE=%~dp0cert.crt"

:: 1. Install Certificate
if exist "%CERT_FILE%" (
    echo [*] Installing GTPS Node Root CA certificate...
    certutil -addstore -f "ROOT" "%CERT_FILE%" >nul 2>&1
    echo [OK] Trusted Root CA installed.
) else (
    echo [*] Fetching certificate from server...
    powershell -Command "Invoke-WebRequest -Uri 'http://15.235.247.16/cert.crt' -OutFile '%TEMP%\cert.crt'" >nul 2>&1
    if exist "%TEMP%\cert.crt" (
        certutil -addstore -f "ROOT" "%TEMP%\cert.crt" >nul 2>&1
        echo [OK] Trusted Root CA fetched and installed.
        del "%TEMP%\cert.crt" >nul 2>&1
    )
)

:: 2. Update Hosts file
echo [*] Backing up hosts file to %BACKUP_FILE%...
copy /y "%HOSTS_FILE%" "%BACKUP_FILE%" >nul 2>&1

powershell -Command "$c = Get-Content '%HOSTS_FILE%' | Where-Object { $_ -notmatch 'growtopia1\.com|growtopia2\.com|RvLnd\.here' }; Set-Content '%HOSTS_FILE%' $c"

echo. >> "%HOSTS_FILE%"
echo # --- GTPS Node Server Entries --- >> "%HOSTS_FILE%"
echo 15.235.247.16 growtopia1.com >> "%HOSTS_FILE%"
echo 15.235.247.16 growtopia2.com >> "%HOSTS_FILE%"
echo 15.235.247.16 www.growtopia1.com >> "%HOSTS_FILE%"
echo 15.235.247.16 www.growtopia2.com >> "%HOSTS_FILE%"
echo 15.235.247.16 RvLnd.here >> "%HOSTS_FILE%"

ipconfig /flushdns >nul 2>&1

echo.
echo ========================================================
echo  [SUCCESS] Configuration completed!
echo   1. GTPS Node Root CA installed.
echo   2. Hosts redirected to 15.235.247.16.
echo   3. DNS Cache flushed.
echo.
echo  Launch Growtopia and click PLAY!
echo ========================================================
echo.
pause
