# win_firewall_add_rule.ps1 - Adds a Windows Firewall inbound rule for a TCP/UDP port.
# Requires: Administrator privileges
# Usage: powershell.exe -ExecutionPolicy Bypass -File win_firewall_add_rule.ps1 -Name "CDP-9222" -Port 9222

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

    [Parameter(Mandatory = $true)]
    [int]$Port,

    [Parameter(Mandatory = $false)]
    [string]$Protocol = "TCP"
)

# Verify administrator privileges
$currentPrincipal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Error "ERROR: This script requires Administrator privileges. Run PowerShell as Administrator."
    exit 1
}

# Validate protocol
$validProtocols = @("TCP", "UDP")
if ($validProtocols -notcontains $Protocol.ToUpper()) {
    Write-Error "ERROR: Protocol must be TCP or UDP, got '$Protocol'."
    exit 1
}

# Validate port range
if ($Port -lt 1 -or $Port -gt 65535) {
    Write-Error "ERROR: Port must be between 1 and 65535, got '$Port'."
    exit 1
}

# Remove existing rule with the same name if it exists
$existingRule = netsh advfirewall firewall show rule name="$Name" 2>&1
if ($LASTEXITCODE -eq 0) {
    Write-Host "Removing existing rule '$Name'..."
    netsh advfirewall firewall delete rule name="$Name" | Out-Null
    if ($LASTEXITCODE -ne 0) {
        Write-Error "ERROR: Failed to remove existing rule '$Name'."
        exit 1
    }
}

# Add the new inbound rule
Write-Host "Adding firewall rule '$Name' for $Protocol port $Port..."
netsh advfirewall firewall add rule name="$Name" dir=in action=allow protocol=$Protocol localport=$Port

if ($LASTEXITCODE -ne 0) {
    Write-Error "ERROR: Failed to add firewall rule '$Name'."
    exit 1
}

Write-Host "OK: Firewall rule '$Name' added - $Protocol inbound on port $Port."
