param(
    [string]$EmmaHome = 'C:\Emma\current'
)

$ErrorActionPreference = 'Stop'

function Update-EmmaLocalFirewallRules {
    param(
        [int]$Port = 3000,
        [string]$AgentExe = $null
    )

    Write-Host 'Aktualisiere Firewall-Regeln fuer Emma Local...'

    Get-NetConnectionProfile -ErrorAction SilentlyContinue |
        Where-Object { $_.NetworkCategory -eq 'Public' } |
        ForEach-Object {
            Set-NetConnectionProfile -InterfaceIndex $_.InterfaceIndex `
                -NetworkCategory Private -ErrorAction SilentlyContinue
        }

    Get-NetFirewallRule -ErrorAction SilentlyContinue |
        Where-Object { $_.DisplayName -like 'Emma Local*' } |
        ForEach-Object {
            Remove-NetFirewallRule -Name $_.Name -ErrorAction SilentlyContinue
        }

    New-NetFirewallRule `
        -DisplayName "Emma Local TCP $Port Eingehend" `
        -Direction Inbound `
        -Protocol TCP `
        -LocalPort $Port `
        -Action Allow `
        -Profile Domain, Private `
        -RemoteAddress LocalSubnet `
        -ErrorAction SilentlyContinue | Out-Null

    New-NetFirewallRule `
        -DisplayName "Emma Local TCP $Port Eingehend blockiert (Public)" `
        -Direction Inbound `
        -Protocol TCP `
        -LocalPort $Port `
        -Action Block `
        -Profile Public `
        -ErrorAction SilentlyContinue | Out-Null

    if ($AgentExe -and (Test-Path $AgentExe)) {
        New-NetFirewallRule `
            -DisplayName 'Emma Local Agent Eingehend' `
            -Direction Inbound `
            -Program $AgentExe `
            -Action Allow `
            -Profile Domain, Private `
            -ErrorAction SilentlyContinue | Out-Null
    }

    Write-Host "Firewall-Port $Port konfiguriert."
}

$agentExe = Join-Path $EmmaHome 'runtime\emma-agent.exe'
Update-EmmaLocalFirewallRules -Port 3000 -AgentExe $agentExe
