# One-time local patch for install-from-folder.ps1 health-check crash on PowerShell 5.1.
# Run from extracted zip folder:  powershell -ExecutionPolicy Bypass -File PATCH-HEALTH.ps1
$ErrorActionPreference = "Stop"
$here = $PSScriptRoot
if (-not $here) { $here = Split-Path -Parent $MyInvocation.MyCommand.Path }
$target = Join-Path $here "install-from-folder.ps1"
if (-not (Test-Path -LiteralPath $target)) {
  throw "install-from-folder.ps1 not found in $here"
}

$content = Get-Content -LiteralPath $target -Raw
$old = @'
    $match = Select-String -Path $envFile -Pattern '^\s*PORT=(\d+)\s*$' | Select-Object -First 1
    if ($match) {
      $ports[[int]$match.Matches.Groups[1].Value] = $true
    }
'@
$new = @'
    try {
      foreach ($line in Get-Content -LiteralPath $envFile) {
        if ($line -match '^\s*PORT=(\d+)\s*$') {
          $ports[[int]$Matches[1]] = $true
          break
        }
      }
    } catch {
      Write-Log "WARN: Could not read .env: $($_.Exception.Message)"
    }
'@

if ($content -notlike "*Select-String -Path `$envFile*") {
  Write-Host "Already patched or script format changed: $target"
  exit 0
}

$content = $content.Replace($old, $new)
Set-Content -LiteralPath $target -Value $content -Encoding UTF8
Write-Host "Patched: $target"
Write-Host "Now run Install.cmd again, or run Open-Setup.cmd to open the UI."
