[CmdletBinding()]
param(
    [string]$SeedHost,
    [uint16]$Port = 4001,
    [string]$Bind = "0.0.0.0",
    [string]$TaskName = "FreedomNetBootstrapNode",
    [switch]$Quiet
)

$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$runner = Join-Path $scriptRoot "run_bootstrap_node.ps1"

if (-not (Test-Path $runner)) {
    throw "run_bootstrap_node.ps1 was not found."
}

if ([string]::IsNullOrWhiteSpace($SeedHost)) {
    throw "SeedHost is required. Example: -SeedHost seed1.imagine-freedom.net"
}

$firewallRuleName = "FreedomNet Bootstrap UDP $Port"
if (-not (Get-NetFirewallRule -DisplayName $firewallRuleName -ErrorAction SilentlyContinue)) {
    New-NetFirewallRule -DisplayName $firewallRuleName `
        -Direction Inbound `
        -Action Allow `
        -Protocol UDP `
        -LocalPort $Port | Out-Null
}

$argumentList = @(
    "-NoProfile",
    "-ExecutionPolicy", "Bypass",
    "-WindowStyle", "Hidden",
    "-File", ('"' + $runner + '"'),
    "-SeedHost", ('"' + $SeedHost + '"'),
    "-Port", [string]$Port,
    "-Bind", ('"' + $Bind + '"')
)

if ($Quiet) {
    $argumentList += "-Quiet"
}

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument ($argumentList -join ' ')
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -RunLevel Highest -LogonType ServiceAccount
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew

Register-ScheduledTask `
    -TaskName $TaskName `
    -Action $action `
    -Trigger $trigger `
    -Principal $principal `
    -Settings $settings `
    -Force | Out-Null

Start-ScheduledTask -TaskName $TaskName

Write-Host "FreedomNet bootstrap node task installed."
Write-Host "  Task: $TaskName"
Write-Host "  Seed: $SeedHost`:$Port"
Write-Host "  Bind: $Bind`:$Port"
