# win_portproxy_remove.ps1 - Removes a netsh portproxy v4tov4 rule.
# Requires: Administrator privileges
# Usage: powershell.exe -ExecutionPolicy Bypass -File win_portproxy_remove.ps1 -ListenPort 9222
#         powershell.exe -ExecutionPolicy Bypass -File win_portproxy_remove.ps1 -ListenAddr 0.0.0.0 -ListenPort 9222

param(
    [Parameter(Mandatory = $true)]
    [int]$ListenPort,

    [Parameter(Mandatory = $false)]
    [string]$ListenAddr = "0.0.0.0"
)

# 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 port
if ($ListenPort -lt 1 -or $ListenPort -gt 65535) {
    Write-Error "ERROR: ListenPort must be between 1 and 65535, got '$ListenPort'."
    exit 1
}

# Check if the portproxy rule exists
$existing = netsh interface portproxy show v4tov4 2>&1 | Select-String "$ListenAddr\s+$ListenPort"
if (-not $existing) {
    Write-Host "INFO: Portproxy for ${ListenAddr}:${ListenPort} does not exist - nothing to remove."
    exit 0
}

# Remove the portproxy rule
Write-Host "Removing portproxy for ${ListenAddr}:${ListenPort}..."
netsh interface portproxy delete v4tov4 listenaddress=$ListenAddr listenport=$ListenPort

if ($LASTEXITCODE -ne 0) {
    Write-Error "ERROR: Failed to remove portproxy for ${ListenAddr}:${ListenPort}."
    exit 1
}

Write-Host "OK: Portproxy for ${ListenAddr}:${ListenPort} removed."
