param(
    [string]$ExePath = (Join-Path $PSScriptRoot "OSMTA.exe"),
    [int]$Port = 7777
)

$ErrorActionPreference = "Stop"

if (-not (Test-Path -LiteralPath $ExePath)) {
    throw "OSMTA executable not found: $ExePath"
}

$resolvedExe = (Resolve-Path -LiteralPath $ExePath).Path
$appName = [System.IO.Path]::GetFileNameWithoutExtension($resolvedExe)

$ruleNames = @(
    "$appName App Inbound",
    "$appName App Outbound",
    "$appName TCP Inbound $Port",
    "$appName TCP Outbound $Port"
)

foreach ($ruleName in $ruleNames) {
    Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue
}

New-NetFirewallRule `
    -DisplayName "$appName App Inbound" `
    -Direction Inbound `
    -Action Allow `
    -Program $resolvedExe `
    -Profile Private,Domain

New-NetFirewallRule `
    -DisplayName "$appName App Outbound" `
    -Direction Outbound `
    -Action Allow `
    -Program $resolvedExe `
    -Profile Private,Domain

New-NetFirewallRule `
    -DisplayName "$appName TCP Inbound $Port" `
    -Direction Inbound `
    -Action Allow `
    -Protocol TCP `
    -LocalPort $Port `
    -Profile Private,Domain

New-NetFirewallRule `
    -DisplayName "$appName TCP Outbound $Port" `
    -Direction Outbound `
    -Action Allow `
    -Protocol TCP `
    -RemotePort $Port `
    -Profile Private,Domain

Write-Host "Firewall rules added for $resolvedExe on TCP port $Port."
