param(
    [string]$ListenAddress = "0.0.0.0",
    [int]$Port = 8010,
    [string]$RuleName = ""
)

$ErrorActionPreference = "Stop"

if ([string]::IsNullOrWhiteSpace($RuleName)) {
    $RuleName = "MyIntranetApp-$Port"
}

$windowsIps = Get-NetIPAddress -AddressFamily IPv4 |
    Where-Object {
        $_.IPAddress -notlike '127.*' `
            -and $_.IPAddress -notlike '169.254*' `
            -and $_.InterfaceAlias -notlike '*WSL*'
    } |
    Select-Object -ExpandProperty IPAddress

$listenAddresses = @($ListenAddress)
if ($ListenAddress -eq "0.0.0.0") {
    $listenAddresses += $windowsIps
}
$listenAddresses = $listenAddresses | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique

foreach ($address in $listenAddresses) {
    netsh interface portproxy delete v4tov4 listenport=$Port listenaddress=$address | Out-Null
}

$existingRule = Get-NetFirewallRule -DisplayName $RuleName -ErrorAction SilentlyContinue
if ($existingRule) {
    Remove-NetFirewallRule -DisplayName $RuleName | Out-Null
}

Write-Host "Removed portproxy and firewall rule for port $Port" -ForegroundColor Yellow
