# Free port 5000 and restart Siraya print agent in current user context.
$ErrorActionPreference = "Continue"
$installDir = Join-Path $env:ProgramFiles "Siraya\Printer"
$startBat = Join-Path $installDir "start-agent.bat"
$dataDir = Join-Path $env:ProgramData "Siraya\Printer"
$runAs = if ($env:USERDOMAIN -and $env:USERNAME) { "$env:USERDOMAIN\$env:USERNAME" } else { $env:USERNAME }

function Free-Port5000 {
  $installDirEsc = [regex]::Escape($installDir)
  try {
    $pids = Get-NetTCPConnection -LocalPort 5000 -State Listen -ErrorAction SilentlyContinue |
      ForEach-Object { $_.OwningProcess } |
      Select-Object -Unique
    foreach ($pid in $pids) {
      if (-not $pid) { continue }
      try {
        $proc = Get-CimInstance Win32_Process -Filter "ProcessId=$pid" -ErrorAction SilentlyContinue
        $cmd = $proc.CommandLine
        if ($cmd -match 'Siraya[\\/]Printer' -or $cmd -match "$installDirEsc" -or ($cmd -match 'index\.js' -and $cmd -match 'node')) {
          Stop-Process -Id $pid -Force -ErrorAction SilentlyContinue
        }
      } catch { }
    }
  } catch { }
}

if (Test-Path -LiteralPath (Join-Path $dataDir "settings.json")) {
  try {
    $settings = Get-Content -LiteralPath (Join-Path $dataDir "settings.json") -Raw | ConvertFrom-Json
    $settings | Add-Member -NotePropertyName port -NotePropertyValue 5000 -Force
    ($settings | ConvertTo-Json -Depth 10) | Set-Content -LiteralPath (Join-Path $dataDir "settings.json") -Encoding UTF8
  } catch { }
}

Free-Port5000

if (-not (Test-Path -LiteralPath $startBat)) {
  exit 1
}

schtasks /End /TN "SirayaPrinterAgent" 2>$null | Out-Null
schtasks /Delete /TN "SirayaPrinterAgent" /F 2>$null | Out-Null
Start-Process -FilePath $startBat -WindowStyle Hidden
Start-Sleep -Seconds 2
schtasks /Create /TN "SirayaPrinterAgent" /TR "`"$startBat`"" /SC ONLOGON /RU $runAs /RL HIGHEST /F | Out-Null
exit 0
