# Stop Siraya print agent (service + scheduled task + node processes).
# Run as Administrator before install, update, or reinstall.
param(
  [scriptblock]$Log = { param($Message) Write-Host $Message }
)

function Stop-SirayaPrinterAgent {
  param(
    [scriptblock]$Log = { param($Message) Write-Host $Message }
  )

  $installDir = Join-Path $env:ProgramFiles "Siraya\Printer"
  $installDirEsc = [regex]::Escape($installDir)

  & $Log "Stopping Siraya print agent..."

  try { schtasks /End /TN "SirayaPrinterAgent" 2>$null | Out-Null } catch { }
  try { net.exe stop SirayaPrinterService 2>$null | Out-Null } catch { }
  Start-Sleep -Seconds 2

  $stopped = 0
  Get-Process -Name node -ErrorAction SilentlyContinue | ForEach-Object {
    try {
      $cmd = (Get-CimInstance Win32_Process -Filter "ProcessId=$($_.Id)" -ErrorAction SilentlyContinue).CommandLine
      if (-not $cmd) { return }
      if ($cmd -match 'Siraya[\\/]Printer' -or $cmd -match "$installDirEsc") {
        Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue
        $script:stopped++
        & $Log "Stopped node PID $($_.Id)"
      }
    } catch { }
  }

  if ($stopped -eq 0) {
    & $Log "No Siraya node processes found (service/task may already be stopped)."
  }

  Start-Sleep -Seconds 2
}

if ($MyInvocation.InvocationName -ne '.') {
  Stop-SirayaPrinterAgent -Log $Log
}
