@echo off
:: Downloaded from the public installer door: the door is tried first.
set "MSEASY_SERVER=https://kit.nz.objectivize.net"
title MSEasy Developer Pack Installer

:: Ensure window never closes silently — re-launch with cmd /k if needed
if not defined MSEASY_INSTALLER_RUNNING (
    set "MSEASY_INSTALLER_RUNNING=1"
    cmd /k "%~f0" %*
    exit /b
)

setlocal EnableExtensions EnableDelayedExpansion
set "SCRIPT_DIR=%~dp0"
set "LOG_FILE=%SCRIPT_DIR%MSEasyInstaller.log"

echo.
echo ===================================================
echo    MSEasy Developer Pack Installer
echo    Windows 10/11
echo ===================================================
echo.
echo Log file: %LOG_FILE%
echo.

> "%LOG_FILE%" echo [INFO] MSEasy installer bootstrap started %DATE% %TIME%
>> "%LOG_FILE%" echo [INFO] Script directory: %SCRIPT_DIR%

echo This will install MSEasy on your computer.
echo It sets up Python, downloads the apps, creates
echo shortcuts, and configures server connectivity.
echo.
echo Press any key to begin or close this window to cancel.
pause > nul
echo.

echo [INFO]  Clearing Windows download-block marker (if present) ...
>> "%LOG_FILE%" echo [INFO] Running Unblock-File ...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
    "$ErrorActionPreference = 'SilentlyContinue'; " ^
    "if (Test-Path '%SCRIPT_DIR%') { Get-ChildItem -Path '%SCRIPT_DIR%' -Recurse -File | Unblock-File; Unblock-File -Path '%~f0' }"
echo [OK]    Unblock done.
>> "%LOG_FILE%" echo [OK] Unblock-File step done.

:: ── Step 1: Find the MSEasy server ──────────────────────────────
:: Install needs the server for everything (UV, installer, Python, app bundle),
:: so there's no offline path — locate it first and fail with clear guidance.
echo [INFO]  Looking for the MSEasy server ...
set "SERVER="
set "SRVFILE=%TEMP%\mseasy_server_probe.txt"
del "%SRVFILE%" >nul 2>&1
:: Probe candidates in PowerShell and write the first reachable URL to a temp
:: file. We read it back with `set /p` rather than capturing stdout via for/f,
:: because for/f backtick capture of PowerShell is fragile on Windows and was
:: silently returning empty (installer aborted with a false "no server" error).
>> "%LOG_FILE%" echo [INFO] Probing for server, writing result to %SRVFILE%
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
    "$ErrorActionPreference='SilentlyContinue'; " ^
    "[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072; " ^
    "$cands=@($env:MSEASY_SERVER,'http://mseasy-server.mesh.nz.objectivize.net:8000','http://100.64.0.1:8000','https://kit.nz.objectivize.net','http://10.0.0.2:8000','http://mseasy-server:8000','http://100.78.68.39:8000'); " ^
    "$found=''; " ^
    "foreach($c in $cands){ if([string]::IsNullOrWhiteSpace($c)){continue}; $c=$c.TrimEnd('/'); $t=4; if($c.StartsWith('https://')){$t=15}; try{ $null=Invoke-WebRequest -Uri ($c+'/health') -UseBasicParsing -TimeoutSec $t; $found=$c; break }catch{} }; " ^
    "Set-Content -LiteralPath '%SRVFILE%' -Value $found -NoNewline -Encoding ascii" >> "%LOG_FILE%" 2>&1
if exist "%SRVFILE%" set /p SERVER=<"%SRVFILE%"
del "%SRVFILE%" >nul 2>&1

if not defined SERVER (
    echo.
    echo Cannot reach MSEasy anywhere - not even its public door ^(https://kit.nz.objectivize.net^).
    echo   Check this computer's internet connection - and its CLOCK: a wrong time or date
    echo   fails every encrypted connection. Then run this installer again.
    echo.
    goto :done
)
echo [OK]    Server found: %SERVER%
>> "%LOG_FILE%" echo [OK] Server found: %SERVER%

:: ── Step 2: Get UV — system copy, else download pinned UV ───────
set "UV_BIN="
where uv >nul 2>&1 && set "UV_BIN=uv" && goto :uv_found
for %%p in (
    "%USERPROFILE%\.local\bin\uv.exe"
    "%LOCALAPPDATA%\uv\uv.exe"
    "%CARGO_HOME%\bin\uv.exe"
) do (
    if exist "%%~p" (
        set "UV_BIN=%%~p"
        goto :uv_found
    )
)

echo [INFO]  Downloading UV from server ...
set "UV_BIN=%SCRIPT_DIR%uv.exe"
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
    "$ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072; try { Invoke-WebRequest -Uri '%SERVER%/install/uv/uv.exe' -OutFile '%UV_BIN%' -UseBasicParsing -TimeoutSec 120; Write-Host '[OK] UV downloaded' } catch { Write-Host ('[FAIL] ' + $_) }" >> "%LOG_FILE%" 2>&1
if not exist "%UV_BIN%" (
    echo [FAIL]  Could not download UV from %SERVER%
    goto :done
)

:uv_found
echo [OK]    UV ready: %UV_BIN%
>> "%LOG_FILE%" echo [OK] UV ready: %UV_BIN%

:: ── Step 3: Get the latest installer from the server ────────────
:: Always pull the newest install_mseasy.py so every install gets current fixes.
set "INSTALLER=%SCRIPT_DIR%install_mseasy.py"
echo [INFO]  Downloading latest installer ...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
    "$ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072; try { Invoke-WebRequest -Uri '%SERVER%/install/installer/unified' -OutFile '%INSTALLER%.tmp' -UseBasicParsing -TimeoutSec 30; Move-Item -Force '%INSTALLER%.tmp' '%INSTALLER%'; Write-Host '[OK] Installer downloaded' } catch { Write-Host ('[FAIL] ' + $_) }; if (Test-Path '%INSTALLER%.tmp') { Remove-Item -Force '%INSTALLER%.tmp' }" >> "%LOG_FILE%" 2>&1

if not exist "%INSTALLER%" (
    echo.
    echo Could not download the installer from %SERVER%.
    echo.
    goto :done
)

:: ── Step 4: Run the installer with UV's Python 3.14 ─────────────
:: Point UV at the server's Python mirror and pass the discovered server so
:: install_mseasy.py doesn't have to re-probe.
set "MSEASY_SERVER=%SERVER%"
set "UV_PYTHON_INSTALL_MIRROR=%SERVER%/install/python-mirror"
echo.
echo [INFO]  Launching MSEasy installer ...
>> "%LOG_FILE%" echo [INFO] Running: "%UV_BIN%" run --python 3.14 "%INSTALLER%"
echo.

"%UV_BIN%" run --python 3.14 "%INSTALLER%" %* 2>&1
set "INSTALL_EXIT=%ERRORLEVEL%"

if not "%INSTALL_EXIT%"=="0" (
    echo.
    echo Installation encountered an error.
    echo Log file: %LOG_FILE%
    echo.
    echo ----- Last 40 log lines -----
    powershell -NoProfile -Command "Get-Content -Path '%LOG_FILE%' -Tail 40"
    echo -----------------------------
    echo.
)
if "%INSTALL_EXIT%"=="0" (
    echo [OK]    Installer finished successfully.
    echo Log file: %LOG_FILE%
)

>> "%LOG_FILE%" echo [INFO] Installer finished with exit code %INSTALL_EXIT%

:done
echo.
echo Press any key to close this window ...
pause > nul
