# Beendet den lokalen 4ever-Wild-Server (start-local.ps1)
param([int]$Port = 9847)

$killed = 0
Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -ErrorAction SilentlyContinue |
  Where-Object { $_.CommandLine -like '*start-local.ps1*' } |
  ForEach-Object {
    Write-Host "Beende Server-Prozess PID $($_.ProcessId)"
    Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
    $killed++
  }

Start-Sleep -Milliseconds 400

try {
  $req = [System.Net.WebRequest]::Create("http://127.0.0.1:$Port/ping")
  $req.Method = "GET"
  $req.Timeout = 1500
  $res = $req.GetResponse()
  $res.Close()
  Write-Host ""
  Write-Host "Hinweis: Port $Port antwortet noch. Evtl. anderes Programm oder verzoegertes Beenden."
  Write-Host "Editor-Fenster mit altem Server schliessen und kurz warten."
} catch {
  Write-Host ""
  if ($killed -gt 0) {
    Write-Host "Server gestoppt ($killed Prozess/e). Jetzt start-local.bat starten."
  } else {
    Write-Host "Kein start-local-Prozess gefunden. Port $Port ist frei oder anderer Dienst."
  }
}

Write-Host ""
Read-Host "Enter zum Beenden"
