#Requires -Version 5.1
# Wrapper script executed by the Windows Service (via NSSM).
# Reads port and config from webadmin.conf, then starts server.js.
param([string]$AppDir = "")
$ErrorActionPreference = "Stop"
if (-not $AppDir) { $AppDir = $PSScriptRoot }

# Read port and BridgeLink server URL from webadmin.conf
$ConfFile = Join-Path $AppDir "webadmin.conf"
if (Test-Path -LiteralPath $ConfFile) {
    Get-Content $ConfFile | ForEach-Object {
        if ($_ -match '^PORT=(\d+)\s*$')                       { $env:PORT = $Matches[1] }
        if ($_ -match '^BRIDGELINK_SERVER_URL=(.+?)\s*$')      { $env:BRIDGELINK_SERVER_URL = $Matches[1] }
        if ($_ -match '^BRIDGELINK_ALLOWED_SERVERS=(.+?)\s*$') { $env:BRIDGELINK_ALLOWED_SERVERS = $Matches[1] }
    }
}
if (-not $env:PORT)                  { $env:PORT = "8444" }
# No BRIDGELINK_SERVER_URL fallback: absent means Same Host — the app auto-authorizes the local BridgeLink server.

$env:SSL_CERT_FILE = Join-Path $env:ProgramData "BridgeLink\certs\server.crt"
$env:SSL_KEY_FILE  = Join-Path $env:ProgramData "BridgeLink\certs\server.key"
# TODO(security): NODE_TLS_REJECT_UNAUTHORIZED=0 was removed — it disabled all TLS verification.
# To trust the BridgeLink server self-signed cert specifically, uncomment and set the path below:
# $env:NODE_EXTRA_CA_CERTS = Join-Path $env:ProgramData "BridgeLink\certs\server.crt"

$NodeExe = Join-Path $env:ProgramData "BridgeLink\.node\node.exe"
if (-not (Test-Path -LiteralPath $NodeExe)) {
    Write-Error "[service-start] Node.js not found at $NodeExe. Re-run the installer to repair."
    exit 1
}

Set-Location $AppDir
& $NodeExe (Join-Path $AppDir "server.js")
