# Shared post-install configuration for the QBooking Print Client.
# Called by install.ps1 (zip flow) and by the NSIS setup.exe after files are
# copied. Must run elevated. Idempotent — safe to re-run on upgrade.
#
#   1. Writes the API URL to %ProgramData%\QBooking\print-client\config.json,
#      preserving the installation guid if one exists (legacy equivalent:
#      C:\qmenu\cloud.bin) so the restaurant link survives reinstalls.
#   2. Registers scheduled task "QBookingPrintClient" — starts hidden at every
#      user logon, restarts on crash — and starts it now.
param(
  [Parameter(Mandatory = $true)][string]$ApiUrl,
  [string]$InstallDir = (Join-Path $env:ProgramFiles "QBooking\PrintClient")
)

$ErrorActionPreference = "Stop"
$taskName = "QBookingPrintClient"

# 1. Config (preserve guid).
$configDir = Join-Path $env:ProgramData "QBooking\print-client"
New-Item -ItemType Directory -Force -Path $configDir | Out-Null
$configPath = Join-Path $configDir "config.json"
$existing = $null
if (Test-Path $configPath) {
  try { $existing = Get-Content $configPath -Raw | ConvertFrom-Json } catch {}
}
$config = @{ apiBaseUrl = $ApiUrl.TrimEnd("/") }
if ($existing -and $existing.guid) { $config.guid = $existing.guid }
$config | ConvertTo-Json | Set-Content -Path $configPath -Encoding UTF8
Write-Output "Wrote $configPath"

# 2. Scheduled task: replace any previous registration, stop a running client.
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
Get-Process -Name "qbooking-print-client" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 1

# wscript + run-hidden.vbs prevents a console window from appearing at logon.
$vbs = Join-Path $InstallDir "run-hidden.vbs"
$exe = Join-Path $InstallDir "qbooking-print-client.exe"
$action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "//B `"$vbs`" `"$exe`"" -WorkingDirectory $InstallDir
$trigger = New-ScheduledTaskTrigger -AtLogOn
$settings = New-ScheduledTaskSettingsSet `
  -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
  -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) `
  -ExecutionTimeLimit ([TimeSpan]::Zero) -Hidden
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings | Out-Null
Start-ScheduledTask -TaskName $taskName
Write-Output "Registered and started scheduled task '$taskName'."

$guid = (Get-Content $configPath -Raw | ConvertFrom-Json).guid
if ($guid) {
  Write-Output "Installation guid (link it in admin > Cloud Printers): $guid"
} else {
  Write-Output "Installation guid will be generated on first run - see admin > Cloud Printers."
}
Write-Output "Logs: $configDir\client.log"
