param(
    [string]$ListenAddress = "0.0.0.0",
    [string]$WslIp = ""
)

$ErrorActionPreference = "Stop"

$apps = @(
    @{ Name = "hm-biz-process"; Port = 8000; RuleName = "HM-BIZ-PROCESS-8000" },
    @{ Name = "my-intranet-app"; Port = 8010; RuleName = "MyIntranetApp-8010" },
    @{ Name = "b17301"; Port = 8020; RuleName = "B17301-8020" }
)

if ([string]::IsNullOrWhiteSpace($WslIp)) {
    $detected = wsl.exe hostname -I 2>$null
    if (-not $detected) {
        throw "WSL IP를 자동으로 찾지 못했습니다. -WslIp 옵션으로 직접 지정해 주세요."
    }

    $WslIp = (($detected -split "\s+") | Where-Object { $_ -match '^\d+\.\d+\.\d+\.\d+$' } | Select-Object -First 1)
    if (-not $WslIp) {
        throw "WSL IP를 자동으로 파싱하지 못했습니다. -WslIp 옵션으로 직접 지정해 주세요."
    }
}

$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

Write-Host "Setting Windows portproxy for all WSL apps..." -ForegroundColor Cyan
Write-Host "WSL IP: $WslIp"

foreach ($app in $apps) {
    $port = [int]$app.Port
    $ruleName = [string]$app.RuleName

    Write-Host ""
    Write-Host "$($app.Name): $port" -ForegroundColor Cyan

    foreach ($address in $listenAddresses) {
        netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$address | Out-Null
        netsh interface portproxy add v4tov4 listenport=$port listenaddress=$address connectport=$port connectaddress=$WslIp
    }

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

    New-NetFirewallRule `
        -DisplayName $ruleName `
        -Direction Inbound `
        -Action Allow `
        -Protocol TCP `
        -LocalPort $port | Out-Null
}

Write-Host ""
Write-Host "Completed." -ForegroundColor Green
Write-Host "Use these URLs from another PC on the intranet:"
if ($windowsIps) {
    foreach ($ip in $windowsIps) {
        Write-Host "hm-biz-process : http://$ip`:8000"
        Write-Host "my-intranet-app: http://$ip`:8010"
        Write-Host "b17301         : http://$ip`:8020"
    }
} else {
    Write-Host "hm-biz-process : http://<Windows-IP>:8000"
    Write-Host "my-intranet-app: http://<Windows-IP>:8010"
    Write-Host "b17301         : http://<Windows-IP>:8020"
}
Write-Host ""
Write-Host "Tip: if WSL restarts and its IP changes, run this script again."
