# win_portproxy_add.ps1 - Adds a netsh portproxy rule (v4tov4) to forward traffic.
# Requires: Administrator privileges
# Usage: powershell.exe -ExecutionPolicy Bypass -File win_portproxy_add.ps1 -ListenPort 9222
#         powershell.exe -ExecutionPolicy Bypass -File win_portproxy_add.ps1 -ListenPort 9222 -ConnectPort 9222 -ListenAddr 0.0.0.0 -ConnectAddr 127.0.0.1

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

    [Parameter(Mandatory = $false)]
    [int]$ConnectPort = 0,  # 0 means use ListenPort

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

    [Parameter(Mandatory = $false)]
    [string]$ConnectAddr = "127.0.0.1"
)

# 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
}

# Default ConnectPort to ListenPort if not specified
if ($ConnectPort -eq 0) {
    $ConnectPort = $ListenPort
}

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

# Remove existing portproxy for the same listenaddress:listenport if it exists
$existing = netsh interface portproxy show v4tov4 2>&1 | Select-String "$ListenAddr\s+$ListenPort"
if ($existing) {
    Write-Host "Removing existing portproxy for ${ListenAddr}:${ListenPort}..."
    netsh interface portproxy delete v4tov4 listenaddress=$ListenAddr listenport=$ListenPort | Out-Null
    if ($LASTEXITCODE -ne 0) {
        Write-Error "ERROR: Failed to remove existing portproxy for ${ListenAddr}:${ListenPort}."
        exit 1
    }
}

# Add the portproxy rule
Write-Host "Adding portproxy: ${ListenAddr}:${ListenPort} -> ${ConnectAddr}:${ConnectPort}..."
netsh interface portproxy add v4tov4 listenaddress=$ListenAddr listenport=$ListenPort connectaddress=$ConnectAddr connectport=$ConnectPort

if ($LASTEXITCODE -ne 0) {
    Write-Error "ERROR: Failed to add portproxy ${ListenAddr}:${ListenPort} -> ${ConnectAddr}:${ConnectPort}."
    exit 1
}

Write-Host "OK: Portproxy added - ${ListenAddr}:${ListenPort} -> ${ConnectAddr}:${ConnectPort}."
