@echo off
setlocal EnableDelayedExpansion
title URVault Server Setup
color 0A

:: ── Self-elevate to Administrator ────────────────────────────────────────────
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo.
    echo  Requesting administrator access...
    echo  Please click Yes on the UAC prompt. A new window will open for setup.
    echo.
    powershell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process -FilePath cmd.exe -ArgumentList '/k \"\"%~f0\"\"' -Verb RunAs -WindowStyle Normal"
    exit /b
)

cd /d "%~dp0"

echo.
echo  ============================================================
echo    URVault Server Setup
echo  ============================================================
echo.

:: ── Terms of Service ─────────────────────────────────────────────────────────
echo  TERMS OF SERVICE
echo  ============================================================
echo.
echo    By installing URVault Server you agree that:
echo.
echo    1. Software is provided AS-IS, no warranty of any kind.
echo    2. URVault LLC is not liable for data loss or server failure.
echo    3. You are responsible for your server security and access control.
echo    4. Your files go to YOUR server -- URVault LLC receives nothing.
echo    5. Governing law: State of Delaware, USA.
echo.
echo    Full terms:     https://urvault.net/terms
echo    Privacy policy: https://urvault.net/privacy
echo.
set /p "TOS_ACCEPT=  Do you accept the Terms of Service? (yes/no): "
set "TOS_ACCEPT=!TOS_ACCEPT: =!"
if /i not "!TOS_ACCEPT!"=="yes" (
    echo.
    echo  Installation cancelled.
    pause
    exit /b 0
)
echo.
echo  Terms accepted. Starting installation -- please keep this window open.
echo  ============================================================
echo.

:: ── Detect running from inside a ZIP / temp extraction ──────────────────────
echo "%~dp0" | findstr /i /c:"\AppData\Local\Temp\" >nul 2>&1
if !errorLevel! equ 0 (
    echo.
    echo  WARNING: This installer appears to be running from a temporary location,
    echo  which usually means it was opened directly from inside a ZIP file.
    echo.
    echo  For a proper installation:
    echo    1. Right-click the ZIP and choose "Extract All"
    echo    2. Open the extracted "urvault-server" folder
    echo    3. Double-click "Install URVault.bat" from that folder
    echo.
    set /p "CONTINUE_ANYWAY=  Continue anyway? (yes/no): "
    set "CONTINUE_ANYWAY=!CONTINUE_ANYWAY: =!"
    if /i not "!CONTINUE_ANYWAY!"=="yes" (
        pause & exit /b 1
    )
    echo.
)

:: ── Verify installer is running from the extracted server folder ─────────────
if not exist "%~dp0install\auto-installer.js" (
    echo.
    echo  ERROR: Missing server files.
    echo.
    echo  This installer must be run from inside the extracted urvault-server folder.
    echo  Steps:
    echo    1. Right-click the zip file and choose "Extract All"
    echo    2. Open the extracted "urvault-server" folder
    echo    3. Double-click "Install URVault.bat" inside that folder
    echo.
    pause & exit /b 1
)
if not exist "%~dp0package.json" (
    echo.
    echo  ERROR: Missing package.json -- server files are incomplete.
    echo  Please re-download the installer package from urvault.net and try again.
    echo.
    pause & exit /b 1
)
if not exist "%~dp0dist\server.js" (
    echo.
    echo  ERROR: Missing dist\server.js -- server bundle is incomplete.
    echo  Please re-download the installer package from urvault.net and try again.
    echo.
    pause & exit /b 1
)
if not exist "%~dp0run-migrations.js" (
    echo.
    echo  ERROR: Missing run-migrations.js -- server files are incomplete.
    echo  Please re-download the installer package from urvault.net and try again.
    echo.
    pause & exit /b 1
)

:: ── PowerShell availability check ────────────────────────────────────────────
powershell -NoProfile -Command "exit 0" >nul 2>&1
if !errorLevel! neq 0 (
    echo.
    echo  ERROR: PowerShell is not available or is blocked on this system.
    echo  This installer requires PowerShell 3.0 or later.
    echo  Contact your IT administrator or check PowerShell execution policy.
    echo.
    pause & exit /b 1
)

:: ── Disk space warning (under 3 GB free on C:) ───────────────────────────────
powershell -NoProfile -Command "if ((Get-PSDrive C -EA SilentlyContinue).Free / 1GB -lt 3) { exit 1 } else { exit 0 }" >nul 2>&1
if !errorLevel! neq 0 (
    echo  WARNING: Less than 3 GB free on C: -- installation or database may fail.
    echo  Consider freeing disk space before continuing.
    echo.
)

:: ── Check winget availability (may be absent on older Windows 10) ─────────────
set "WINGET_OK=0"
winget --version >nul 2>&1
if !errorLevel! equ 0 set "WINGET_OK=1"

:: ── [1/6] Node.js ─────────────────────────────────────────────────────────────
echo  [1/6] Node.js...
node --version >nul 2>&1
if %errorLevel% neq 0 (
    echo        Not found -- installing automatically...
    if "!WINGET_OK!"=="1" (
        winget install --id OpenJS.NodeJS.LTS -e --silent --accept-package-agreements --accept-source-agreements
    ) else (
        echo.
        echo  ERROR: winget not available on this system.
        echo  Please install Node.js manually from https://nodejs.org/
        echo  then re-run this installer.
        pause & exit /b 1
    )
    for /f "usebackq delims=" %%p in (`powershell -NoProfile -Command "[Environment]::GetEnvironmentVariable('PATH','Machine')"`) do (
        set "PATH=%%p;!PATH!"
    )
    node --version >nul 2>&1
    if !errorLevel! neq 0 (
        echo.
        echo  ERROR: Node.js install failed.
        echo  Download from https://nodejs.org/ then re-run this installer.
        pause & exit /b 1
    )
)
for /f %%v in ('node --version') do echo        %%v  OK

:: ── [2/6] MySQL ───────────────────────────────────────────────────────────────
echo  [2/6] Setting up database...
set "MYSQL_WAS_FRESH=0"
set "MYSQL_FOUND=0"
set "MYSQL_SVC_BIN="

:: Scan common install paths -- add newest found version only
for %%v in (9.2 9.1 9.0 8.4 8.3 8.2 8.1 8.0 5.7) do (
    if not defined MYSQL_PATH_ADDED (
        if exist "C:\Program Files\MySQL\MySQL Server %%v\bin\mysql.exe" (
            set "PATH=!PATH!;C:\Program Files\MySQL\MySQL Server %%v\bin"
            set "MYSQL_PATH_ADDED=1"
        )
    )
)

:: Check CLI
mysql --version >nul 2>&1
if !errorLevel! equ 0 set "MYSQL_FOUND=1"

:: Check for existing MySQL service (installed but bin not in PATH)
if "!MYSQL_FOUND!"=="0" (
    powershell -NoProfile -Command "if (Get-Service 'MySQL*' -EA SilentlyContinue) { exit 0 } else { exit 1 }" >nul 2>&1
    if !errorLevel! equ 0 (
        powershell -NoProfile -Command "$s=Get-WmiObject Win32_Service | Where-Object {$_.Name -like 'MySQL*'} | Select-Object -First 1; if($s){$p=$s.PathName.Trim([char]34); Split-Path $p -Parent}" > "%TEMP%\urvault_mysql_bin.txt" 2>nul
        set /p MYSQL_SVC_BIN=<"%TEMP%\urvault_mysql_bin.txt"
        if defined MYSQL_SVC_BIN (
            if exist "!MYSQL_SVC_BIN!\mysql.exe" (
                set "PATH=!PATH!;!MYSQL_SVC_BIN!"
                set "MYSQL_FOUND=1"
            )
        )
    )
)

:: Install via winget if MySQL not found at all
if "!MYSQL_FOUND!"=="0" (
    if "!WINGET_OK!"=="0" (
        echo.
        echo  ERROR: MySQL is not installed and winget is not available.
        echo  Please install MySQL 8.4 from https://dev.mysql.com/downloads/installer/
        echo  then re-run this installer.
        pause & exit /b 1
    )
    echo        Installing MySQL...
    winget install --id Oracle.MySQL -e --silent --accept-package-agreements --accept-source-agreements
    for /f "usebackq delims=" %%p in (`powershell -NoProfile -Command "[Environment]::GetEnvironmentVariable('PATH','Machine')"`) do (
        set "PATH=%%p;!PATH!"
    )
    for %%v in (9.2 9.1 9.0 8.4 8.3 8.2 8.1 8.0) do (
        if exist "C:\Program Files\MySQL\MySQL Server %%v\bin\mysql.exe" (
            set "PATH=!PATH!;C:\Program Files\MySQL\MySQL Server %%v\bin"
        )
    )
)

:: Initialize MySQL if no service exists (winget installs binaries only -- no service, no data dir)
powershell -NoProfile -Command "if (Get-Service 'MySQL*' -EA SilentlyContinue) { exit 0 } else { exit 1 }" >nul 2>&1
if !errorLevel! neq 0 (
    set "MYSQL_INIT_BIN="
    set "MYSQL_INIT_VER="
    for %%v in (9.2 9.1 9.0 8.4 8.3 8.2 8.1 8.0) do (
        if exist "C:\Program Files\MySQL\MySQL Server %%v\bin\mysqld.exe" (
            if not defined MYSQL_INIT_BIN (
                set "MYSQL_INIT_BIN=C:\Program Files\MySQL\MySQL Server %%v\bin"
                set "MYSQL_INIT_VER=%%v"
            )
        )
    )
    if defined MYSQL_INIT_BIN (
        echo        Initializing database ^(~15 seconds^)...
        if not exist "C:\ProgramData\MySQL\MySQL Server !MYSQL_INIT_VER!" mkdir "C:\ProgramData\MySQL\MySQL Server !MYSQL_INIT_VER!" >nul 2>&1
        if not exist "C:\ProgramData\MySQL\MySQL Server !MYSQL_INIT_VER!\Data" mkdir "C:\ProgramData\MySQL\MySQL Server !MYSQL_INIT_VER!\Data" >nul 2>&1
        set "MYSQL_INI=C:\ProgramData\MySQL\MySQL Server !MYSQL_INIT_VER!\my.ini"
        > "!MYSQL_INI!" (
            echo [mysqld]
            echo basedir=C:/Program Files/MySQL/MySQL Server !MYSQL_INIT_VER!/
            echo datadir=C:/ProgramData/MySQL/MySQL Server !MYSQL_INIT_VER!/Data
            echo port=3306
        )
        "!MYSQL_INIT_BIN!\mysqld.exe" "--defaults-file=!MYSQL_INI!" --initialize-insecure --console >nul 2>&1
        :: Verify initialization actually populated the data directory
        powershell -NoProfile -Command "if ((Get-ChildItem 'C:\ProgramData\MySQL\MySQL Server !MYSQL_INIT_VER!\Data' -EA SilentlyContinue | Measure-Object).Count -gt 0) { exit 0 } else { exit 1 }" >nul 2>&1
        if !errorLevel! neq 0 (
            echo.
            echo  ERROR: MySQL database initialization failed ^(data directory empty^).
            echo  Ensure you have write access to C:\ProgramData and at least 1 GB free disk space,
            echo  then re-run this installer.
            echo.
            pause & exit /b 1
        )
        powershell -NoProfile -ExecutionPolicy Bypass -Command "New-Service -Name MySQL84 -BinaryPathName (([char]34+'!MYSQL_INIT_BIN!\mysqld.exe'+[char]34)+' '+([char]34+'--defaults-file=!MYSQL_INI!'+[char]34)) -StartupType Automatic -DisplayName 'MySQL 8.4'" >nul 2>&1
        set "MYSQL_WAS_FRESH=1"
    )
)

:: Start MySQL service
powershell -NoProfile -Command "$svc=Get-Service 'MySQL*' -EA SilentlyContinue | Select-Object -First 1; if($svc -and $svc.Status -ne 'Running'){Start-Service $svc.Name -EA SilentlyContinue}" >nul 2>&1

:: Wait up to 60s for MySQL to accept connections on port 3306
set "MYSQL_READY=0"
for /L %%i in (1,1,30) do (
    if "!MYSQL_READY!"=="0" (
        powershell -NoProfile -Command "try{$t=New-Object Net.Sockets.TcpClient;$t.Connect('127.0.0.1',3306);$t.Close();exit 0}catch{exit 1}" >nul 2>&1
        if !errorLevel! equ 0 (
            set "MYSQL_READY=1"
        ) else (
            timeout /t 2 /nobreak >nul
        )
    )
)

:: Verify CLI available
mysql --version >nul 2>&1
if !errorLevel! neq 0 (
    echo.
    echo  ERROR: MySQL CLI not found after setup.
    echo  Please add the MySQL bin folder to PATH manually and re-run.
    pause & exit /b 1
)

:: Verify port is responding
if "!MYSQL_READY!"=="0" (
    echo.
    echo  ERROR: MySQL is not responding on port 3306.
    echo  Open Services ^(services.msc^) and ensure the MySQL service is Running,
    echo  then re-run this installer.
    echo.
    pause & exit /b 1
)

if "!MYSQL_WAS_FRESH!"=="1" (
    echo        Installed OK
) else (
    echo        Found OK
)

:: ── [3/6] MySQL root credentials ──────────────────────────────────────────────
echo  [3/6] Configuring database...
set "URVAULT_MYSQL_ROOT_PW="
set "URVAULT_STD_PW=URVaultSvr2026"

:: Attempt 1: blank password (fresh install with --initialize-insecure)
mysql -u root --password="" -e "SELECT 1;" >nul 2>&1
if !errorLevel! equ 0 (
    mysql -u root --password="" -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '!URVAULT_STD_PW!'; FLUSH PRIVILEGES;" >nul 2>&1
    set "URVAULT_MYSQL_ROOT_PW=!URVAULT_STD_PW!"
    goto :mysql_auth_done
)

:: Attempt 2: our standard password (re-install scenario)
mysql -u root -p"!URVAULT_STD_PW!" -e "SELECT 1;" >nul 2>&1
if !errorLevel! equ 0 (
    set "URVAULT_MYSQL_ROOT_PW=!URVAULT_STD_PW!"
    goto :mysql_auth_done
)

:: Attempt 3: detect temp password from MySQL error log (MySQL installer sets one)
echo        Detecting credentials...
powershell -NoProfile -Command "try { $roots = 'C:\ProgramData\MySQL','C:\Program Files\MySQL'; $found = $null; foreach ($root in $roots) { if (!Test-Path $root) { continue }; $dirs = Get-ChildItem $root -Directory -EA SilentlyContinue | Sort-Object Name -Descending; foreach ($d in $dirs) { foreach ($dd in ($d.FullName+'\Data'),$d.FullName) { $f = Get-ChildItem $dd -Filter '*.err' -EA SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1; if ($f) { $m = Select-String -Path $f.FullName -Pattern 'temporary password is generated for root@localhost: (.+)$'; if ($m) { $found = $m.Matches[0].Groups[1].Value.Trim(); break } } }; if ($found) { break } }; if ($found) { break } }; if ($found) { $found } } catch {}" > "%TEMP%\urvault_mysql_pw.txt" 2>nul
set "TEMP_PW="
set /p TEMP_PW=<"%TEMP%\urvault_mysql_pw.txt"
if defined TEMP_PW (
    mysql -u root -p"!TEMP_PW!" --connect-expired-password -e "SELECT 1;" >nul 2>&1
    if !errorLevel! equ 0 (
        mysql -u root -p"!TEMP_PW!" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '!URVAULT_STD_PW!'; FLUSH PRIVILEGES;" >nul 2>&1
        set "URVAULT_MYSQL_ROOT_PW=!URVAULT_STD_PW!"
        goto :mysql_auth_done
    )
)

:: Attempt 4: silent auto-reset via --init-file (unknown existing password)
echo        Resetting credentials...
set "MYSQL_RESET_BIN="
powershell -NoProfile -Command "(Get-Command mysql -EA SilentlyContinue).Source | Split-Path -Parent" > "%TEMP%\urvault_mysql_dir.txt" 2>nul
set /p MYSQL_RESET_BIN=<"%TEMP%\urvault_mysql_dir.txt"
if not defined MYSQL_RESET_BIN if defined MYSQL_SVC_BIN set "MYSQL_RESET_BIN=!MYSQL_SVC_BIN!"
if not defined MYSQL_RESET_BIN (
    for %%v in (9.2 9.1 9.0 8.4 8.3 8.2 8.1 8.0) do (
        if exist "C:\Program Files\MySQL\MySQL Server %%v\bin\mysqld.exe" (
            if not defined MYSQL_RESET_BIN set "MYSQL_RESET_BIN=C:\Program Files\MySQL\MySQL Server %%v\bin"
        )
    )
)
if defined MYSQL_RESET_BIN (
    set "RESET_SQL=%TEMP%\urvault_mysql_reset.sql"
    echo ALTER USER 'root'@'localhost' IDENTIFIED BY '!URVAULT_STD_PW!';> "!RESET_SQL!"
    echo FLUSH PRIVILEGES;>> "!RESET_SQL!"
    :: Stop service and kill any stray mysqld processes for a clean reset
    powershell -NoProfile -Command "Stop-Service (Get-Service 'MySQL*' | Select-Object -First 1).Name -Force -EA SilentlyContinue" >nul 2>&1
    timeout /t 3 /nobreak >nul
    taskkill /f /im mysqld.exe >nul 2>&1
    timeout /t 2 /nobreak >nul
    powershell -NoProfile -Command "$s=Get-WmiObject Win32_Service|Where-Object{$_.Name -like 'MySQL*'}|Select-Object -First 1; if($s -and $s.PathName -match '--defaults-file=([^""]+)'){$Matches[1].Trim()}" > "%TEMP%\urvault_defaults.txt" 2>nul
    set "MYSQL_DEFAULTS_FILE="
    set /p MYSQL_DEFAULTS_FILE=<"%TEMP%\urvault_defaults.txt"
    :: Fallback: scan ProgramData for my.ini (our installer always writes it here)
    if not defined MYSQL_DEFAULTS_FILE (
        for %%v in (9.2 9.1 9.0 8.4 8.3 8.2 8.1 8.0 5.7) do (
            if not defined MYSQL_DEFAULTS_FILE (
                if exist "C:\ProgramData\MySQL\MySQL Server %%v\my.ini" (
                    set "MYSQL_DEFAULTS_FILE=C:\ProgramData\MySQL\MySQL Server %%v\my.ini"
                )
            )
        )
    )
    if defined MYSQL_DEFAULTS_FILE (
        start /b "" "!MYSQL_RESET_BIN!\mysqld.exe" "--defaults-file=!MYSQL_DEFAULTS_FILE!" "--init-file=!RESET_SQL!"
    ) else (
        start /b "" "!MYSQL_RESET_BIN!\mysqld.exe" "--init-file=!RESET_SQL!"
    )
    timeout /t 25 /nobreak >nul
    "!MYSQL_RESET_BIN!\mysqladmin.exe" -u root "-p!URVAULT_STD_PW!" shutdown >nul 2>&1
    timeout /t 4 /nobreak >nul
    taskkill /f /im mysqld.exe >nul 2>&1
    timeout /t 3 /nobreak >nul
    powershell -NoProfile -Command "Start-Service (Get-Service 'MySQL*' | Select-Object -First 1).Name -EA SilentlyContinue" >nul 2>&1
    :: Retry up to 5x (15s total) for MySQL to accept connections after reset
    set "MYSQL_RESET_OK="
    for /L %%r in (1,1,5) do (
        if not defined MYSQL_RESET_OK (
            timeout /t 3 /nobreak >nul
            mysql -u root -p"!URVAULT_STD_PW!" -e "SELECT 1;" >nul 2>&1
            if !errorLevel! equ 0 set "MYSQL_RESET_OK=1"
        )
    )
    if defined MYSQL_RESET_OK (
        set "URVAULT_MYSQL_ROOT_PW=!URVAULT_STD_PW!"
        goto :mysql_auth_done
    )
)

:: All automatic attempts failed
echo.
echo  ERROR: Could not configure MySQL automatically.
echo  Please contact support at support@urvault.net
echo.
pause & exit /b 1

:mysql_auth_done
echo        OK

:: Pre-create URVault database now while we have confirmed MySQL access
:: This bypasses mysql-CLI-in-PATH issues inside the Node auto-installer subprocess
powershell -NoProfile -Command "[System.Guid]::NewGuid().ToString('N')" > "%TEMP%\urvault_dbpw.txt" 2>nul
set "URVAULT_DB_PASSWORD="
set /p URVAULT_DB_PASSWORD=<"%TEMP%\urvault_dbpw.txt"
set "URVAULT_DB_NAME=urvault"
set "URVAULT_DB_USER=urvault"
if defined URVAULT_DB_PASSWORD (
    mysql -u root -p"!URVAULT_MYSQL_ROOT_PW!" -e "CREATE DATABASE IF NOT EXISTS urvault; CREATE USER IF NOT EXISTS 'urvault'@'localhost' IDENTIFIED BY '!URVAULT_DB_PASSWORD!'; ALTER USER 'urvault'@'localhost' IDENTIFIED BY '!URVAULT_DB_PASSWORD!'; GRANT ALL PRIVILEGES ON urvault.* TO 'urvault'@'localhost'; FLUSH PRIVILEGES;" >nul 2>&1
    if !errorLevel! equ 0 (
        set "URVAULT_DB_READY=1"
        echo        Database created OK
    ) else (
        echo        Database pre-creation deferred to setup step
    )
)

:: ── [4/6] Install Node.js dependencies ────────────────────────────────────────
echo  [4/6] Installing dependencies...
call npm install --omit=dev
if %errorLevel% neq 0 (
    echo  WARNING: npm install reported errors. Continuing...
)

:: ── [5/6] Configure and install URVault ───────────────────────────────────────
echo  [5/6] Configuring URVault...
echo.

:: Re-inject MySQL bin into PATH right before calling node so child processes find it
for %%v in (9.2 9.1 9.0 8.4 8.3 8.2 8.1 8.0) do (
    if exist "C:\Program Files\MySQL\MySQL Server %%v\bin\mysql.exe" (
        if not defined MYSQL_BIN_REINJECTED (
            set "PATH=C:\Program Files\MySQL\MySQL Server %%v\bin;!PATH!"
            set "MYSQL_BIN_REINJECTED=1"
        )
    )
)

:: Verify MySQL CLI is visible before handing off to node
mysql --version >nul 2>&1
if !errorLevel! neq 0 (
    echo.
    echo  ERROR: MySQL CLI is not accessible ^(not in PATH^).
    echo  Open Services ^(services.msc^) to verify MySQL is Running,
    echo  then re-run this installer.
    pause & exit /b 1
)

:: ── Port selection ────────────────────────────────────────────────────────────
set "URVAULT_PORT=5173"
:: Only check for conflict if URVaultServer is not already running (re-install scenario)
powershell -NoProfile -Command "if (Get-Service 'URVaultServer' -EA SilentlyContinue | Where-Object {$_.Status -eq 'Running'}) { exit 0 } else { exit 1 }" >nul 2>&1
if !errorLevel! neq 0 (
    powershell -NoProfile -Command "try{$t=New-Object Net.Sockets.TcpClient;$t.Connect('127.0.0.1',5173);$t.Close();exit 0}catch{exit 1}" >nul 2>&1
    if !errorLevel! equ 0 (
        echo.
        echo  WARNING: Port 5173 is already in use by another process.
        echo  URVault needs a free port to run its web interface.
        echo.
        echo  Options:
        echo    - Enter an alternate port ^(e.g. 5174, 8080, 3000^)
        echo    - Press Enter to use 5173 anyway
        echo.
        set /p "URVAULT_PORT=  Enter port number [5173]: "
        set "URVAULT_PORT=!URVAULT_PORT: =!"
        if "!URVAULT_PORT!"=="" set "URVAULT_PORT=5173"
        echo !URVAULT_PORT!| findstr /r "^[0-9][0-9]*$" >nul 2>&1
        if !errorLevel! neq 0 (
            echo        Invalid port number. Using default 5173.
            set "URVAULT_PORT=5173"
        )
        echo.
    )
)

node install/auto-installer.js --auto
if !errorLevel! neq 0 (
    echo.
    echo  ============================================================
    echo   ERROR: Setup failed. Review the output above for details.
    echo.
    echo   Common causes:
    echo    - MySQL stopped between steps ^(restarting may help^)
    echo    - Network error downloading Cloudflare tunnel binary
    echo.
    echo   For help: support@urvault.net
    echo  ============================================================
    pause & exit /b 1
)

:: ── Read actual port from .env (auto-installer may have used a custom port) ────
for /f "tokens=1,2 delims==" %%k in (.env) do (
    if "%%k"=="PORT" set "URVAULT_PORT=%%l"
)
if not defined URVAULT_PORT set "URVAULT_PORT=5173"

:: ── Firewall rule ──────────────────────────────────────────────────────────────
echo        Configuring firewall...
netsh advfirewall firewall delete rule name="URVault Server" >nul 2>&1
netsh advfirewall firewall add rule name="URVault Server" dir=in action=allow protocol=TCP localport=!URVAULT_PORT! >nul 2>&1
echo        Firewall rule added ^(port !URVAULT_PORT!^)

:: ── [6/6] Windows service (auto-start on boot) ────────────────────────────────
echo.
echo  [6/6] Installing Windows service...

if not exist nssm.exe (
    echo        Downloading service manager...
    powershell -NoProfile -ExecutionPolicy Bypass -Command ^
        "try { Invoke-WebRequest -Uri 'https://nssm.cc/release/nssm-2.24.zip' -OutFile $env:TEMP\nssm.zip -TimeoutSec 30; Expand-Archive $env:TEMP\nssm.zip -DestinationPath $env:TEMP\nssm_extract -Force; Copy-Item $env:TEMP\nssm_extract\nssm-2.24\win64\nssm.exe . ; Remove-Item $env:TEMP\nssm.zip,$env:TEMP\nssm_extract -Recurse -Force; Write-Host '       nssm OK' } catch { Write-Host '       nssm download failed -- using task scheduler fallback' }" 2>&1
)

if exist nssm.exe (
    nssm stop URVaultServer >nul 2>&1
    nssm remove URVaultServer confirm >nul 2>&1
    nssm install URVaultServer "%SystemRoot%\System32\cmd.exe"
    nssm set URVaultServer AppParameters "/c \"%~dp0start-server.bat\" >> \"%~dp0server.log\" 2>&1"
    nssm set URVaultServer AppDirectory "%~dp0"
    nssm set URVaultServer DisplayName "URVault Server"
    nssm set URVaultServer Description "URVault personal cloud backup server"
    nssm set URVaultServer Start SERVICE_AUTO_START
    nssm start URVaultServer >nul 2>&1
    echo        Service installed and started ^(auto-starts on boot^)
) else (
    schtasks /delete /tn "URVaultServer" /f >nul 2>&1
    schtasks /create /f /tn "URVaultServer" /sc ONSTART /rl HIGHEST /ru SYSTEM ^
        /tr "cmd /c cd /d \"%~dp0\" && start-server.bat >> server.log 2>&1" /delay 0000:30 >nul 2>&1
    if !errorLevel! equ 0 (
        schtasks /run /tn "URVaultServer" >nul 2>&1
        echo        Scheduled task created ^(starts on boot^)
    ) else (
        echo        Could not install service. Start manually: double-click start-server.bat
    )
)

:: ── Verify server is responding ───────────────────────────────────────────────
echo.
echo        Waiting for server to start...
set "SRV_READY=0"
for /L %%w in (1,1,6) do (
    if "!SRV_READY!"=="0" (
        timeout /t 3 /nobreak >nul
        powershell -NoProfile -Command "try{$t=New-Object Net.Sockets.TcpClient;$t.Connect('127.0.0.1',!URVAULT_PORT!);$t.Close();exit 0}catch{exit 1}" >nul 2>&1
        if !errorLevel! equ 0 set "SRV_READY=1"
    )
)
if "!SRV_READY!"=="1" (
    echo        Server is running on port !URVAULT_PORT!
) else (
    echo        Server did not respond yet -- it may still be initialising.
    echo        If it does not start within 60 seconds, check server.log in this folder.
)

:: ── Done ──────────────────────────────────────────────────────────────────────
echo.
echo  ============================================================
echo    Setup Complete!
echo  ============================================================
echo.
echo    Open your browser to finish setup:
echo.
echo      http://localhost:!URVAULT_PORT!
echo.
echo    Then pair your phone using the URVault app.
echo.
echo    The server starts automatically on boot.
echo    To start it now if not already running:
echo      double-click start-server.bat
echo.
pause
