#Requires -RunAsAdministrator

param(
    [Parameter(Mandatory=$true)]
    [string]$DnsServer,

    [Parameter(Mandatory=$false)]
    [string]$InterfaceAlias
)

$ErrorActionPreference = "Stop"

# Verify running as Administrator
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]$identity
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Error "This script must be run as a machine Administrator."
    exit 1
}

# Verify Nebula service is running
$nebulaSvc = Get-Service -Name "nebula" -ErrorAction SilentlyContinue
if (-not $nebulaSvc -or $nebulaSvc.Status -ne "Running") {
    Write-Error "Nebula service is not running. Run install-nebula.ps1 first."
    exit 1
}

# Validate DNS server is a valid IP
if (-not ($DnsServer -as [System.Net.IPAddress])) {
    Write-Error "Invalid DNS server address: $DnsServer"
    exit 1
}

# Default to the Nebula tunnel adapter — physical adapters should keep their local DNS
if ($InterfaceAlias) {
    $adapters = Get-NetAdapter -Name $InterfaceAlias -ErrorAction SilentlyContinue
    if (-not $adapters) {
        Write-Error "Network adapter '$InterfaceAlias' not found."
        exit 1
    }
} else {
    $adapters = Get-NetAdapter -Name "nebula1" -ErrorAction SilentlyContinue
    if (-not $adapters) {
        Write-Error "Nebula adapter 'nebula1' not found. Is the Nebula service running?"
        exit 1
    }
}

foreach ($adapter in $adapters) {
    Write-Host "Setting DNS to $DnsServer on '$($adapter.Name)'..."
    Set-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -ServerAddresses $DnsServer
}

# Verify
foreach ($adapter in $adapters) {
    $dns = Get-DnsClientServerAddress -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4
    if ($dns.ServerAddresses -contains $DnsServer) {
        Write-Host "Verified: '$($adapter.Name)' DNS is now $DnsServer"
    } else {
        Write-Error "Failed to verify DNS on '$($adapter.Name)'"
        exit 1
    }
}
