<#
.SYNOPSIS
    Installs Traefik as a Windows service that routes admin HTTP traffic to whichever
    OtOpcUa.Host node holds the admin role-leader (via /health/active).

.DESCRIPTION
    Downloads the Traefik Windows binary into $InstallRoot, drops traefik.yml +
    traefik-dynamic.yml from this directory next to it, and registers Traefik as a
    Windows service via sc.exe with restart-on-failure.

    Companion to Install-Services.ps1. Run on the box that fronts the admin HTTP
    traffic (typically a separate node from OtOpcUaHost, or co-located on the
    primary admin node).

.PARAMETER InstallRoot
    Where the Traefik binary + config land. Default 'C:\Program Files\Traefik'.

.PARAMETER TraefikVersion
    Traefik version to download. Default 'v3.1.6'.

.EXAMPLE
    .\Install-Traefik.ps1 -InstallRoot 'C:\Program Files\Traefik'
#>
[CmdletBinding()]
param(
    [string]$InstallRoot = 'C:\Program Files\Traefik',
    [string]$TraefikVersion = 'v3.1.6'
)

$ErrorActionPreference = 'Stop'

if (-not (Test-Path $InstallRoot)) {
    New-Item -ItemType Directory -Path $InstallRoot | Out-Null
}

$zip = Join-Path $env:TEMP "traefik-$TraefikVersion.zip"
$url = "https://github.com/traefik/traefik/releases/download/$TraefikVersion/traefik_${TraefikVersion}_windows_amd64.zip"

Write-Host "Downloading Traefik $TraefikVersion..."
Invoke-WebRequest -Uri $url -OutFile $zip
Expand-Archive -Path $zip -DestinationPath $InstallRoot -Force
Remove-Item $zip

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Copy-Item -Force (Join-Path $scriptDir 'traefik.yml') $InstallRoot
Copy-Item -Force (Join-Path $scriptDir 'traefik-dynamic.yml') (Join-Path $InstallRoot 'dynamic.yml')

# Traefik reads dynamic.yml from /etc/traefik on Linux; on Windows place it next to the
# binary and point the file provider at it. Edit traefik.yml's `filename:` if you want
# to change the location.
(Get-Content -Raw (Join-Path $InstallRoot 'traefik.yml')) `
    -replace '/etc/traefik/dynamic.yml', (Join-Path $InstallRoot 'dynamic.yml').Replace('\', '/') `
    | Set-Content (Join-Path $InstallRoot 'traefik.yml')

Write-Host "Installing Traefik Windows service..."
& sc.exe create OtOpcUaTraefik binPath= "`"$InstallRoot\traefik.exe`" --configFile=`"$InstallRoot\traefik.yml`"" `
    DisplayName= 'OtOpcUa Traefik (admin HTTP front door)' `
    start= auto | Out-Null

& sc.exe failure OtOpcUaTraefik reset= 86400 actions= restart/5000/restart/30000/restart/60000 | Out-Null

Write-Host ""
Write-Host "Installed OtOpcUaTraefik. Edit:"
Write-Host "  $InstallRoot\dynamic.yml  (router + service definitions)"
Write-Host "Start with:"
Write-Host "  sc.exe start OtOpcUaTraefik"
Write-Host ""
Write-Host "Traefik dashboard: http://localhost:8080  (turn off api.insecure in production)"
