@echo off
setlocal EnableExtensions EnableDelayedExpansion
title Project Zomboid - server setup
mode con: cols=100 lines=45 >nul 2>&1

echo.
echo   ===========================================================
echo     PROJECT ZOMBOID  -  server setup
echo   ===========================================================
echo.
echo   This will:
echo     1. turn on Steam's "Allow downloads during gameplay"
echo     2. install 8 mods that Steam cannot serve any more
echo     3. restore 129 game files missing from the Steam build
echo.
echo   It does not touch your saves or your other mods, and it
echo   backs up every file it edits. Nothing needs admin rights.
echo.
echo   ===========================================================
echo.

rem ---- Windows 10 1803+ ships curl.exe; older builds do not -------------
if not exist "%SystemRoot%\System32\curl.exe" (
    echo   [X] This needs Windows 10 version 1803 or newer.
    echo       Follow the manual instructions on the web page instead.
    echo.
    pause
    exit /b 1
)
set "CURL=%SystemRoot%\System32\curl.exe"

rem ---- find whichever address actually works from here ------------------
echo   Finding the server...
set "BASE="
for %%U in (
    "https://amp.tail1f3f12.ts.net"
    "http://100.72.119.93:8088"
    "http://192.168.1.220:8088"
) do (
    if not defined BASE (
        "%CURL%" -fsS --max-time 6 -o nul "%%~U/ping.txt" >nul 2>&1
        if !errorlevel! equ 0 (
            set "BASE=%%~U"
            echo       reachable: %%~U
        )
    )
)

if not defined BASE (
    echo.
    echo   [X] Cannot reach the setup server on any known address.
    echo.
    echo       If you are joining from outside the house you need to be
    echo       signed in to Tailscale first. Install it from
    echo       https://tailscale.com/download, accept the invite you were
    echo       sent, then run this file again.
    echo.
    pause
    exit /b 1
)

rem ---- fetch and run the real script ------------------------------------
set "PS1=%TEMP%\pz-setup.ps1"
"%CURL%" -fL --retry 3 --retry-delay 2 -o "%PS1%" "%BASE%/pz-setup.ps1"
if errorlevel 1 (
    echo.
    echo   [X] Could not download the setup script from %BASE%
    echo.
    pause
    exit /b 1
)

powershell -NoProfile -ExecutionPolicy Bypass -File "%PS1%" -BaseUrl "%BASE%"
set "RC=%errorlevel%"

del "%PS1%" >nul 2>&1

if not "%RC%"=="0" (
    echo.
    echo   Setup did not finish. The web page has manual instructions
    echo   that do the same thing by hand.
)

echo.
pause
endlocal
exit /b %RC%
