param(
    [string]$InstallDirectory = (Split-Path -Path $PSScriptRoot -Parent),
    [string]$AgentArguments = "",
    # Used by the logon Run entry: an already-running agent is success, not an
    # error, so sign-ins after a live session never surface a spurious failure.
    [switch]$IgnoreAlreadyRunning
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$agentExe = Join-Path $InstallDirectory "agent\IAUWP.Agent.exe"
if (-not (Test-Path -Path $agentExe)) {
    throw "Agent executable was not found at '$agentExe'."
}

$runDirectory = Join-Path $InstallDirectory "run"
New-Item -ItemType Directory -Path $runDirectory -Force | Out-Null
$pidPath = Join-Path $runDirectory "agent.pid"

if (Test-Path -Path $pidPath) {
    $existingPid = Get-Content -Path $pidPath -Raw
    if ($existingPid -match '^\s*\d+\s*$') {
        $existingProcess = Get-Process -Id ([int]$existingPid) -ErrorAction SilentlyContinue
        # 2026-07-29 SwiftHub reboot incident: after a reboot the stale pid can
        # belong to ANY process (pid reuse), and concluding "already running"
        # from bare pid existence made the logon revival a silent no-op â€” the
        # agent stayed dead. Only a process that is actually THIS install's
        # agent counts; anything else is a stale file to clear. The agent's own
        # session mutex remains the authoritative duplicate guard regardless.
        $existingIsAgent = $false
        if ($existingProcess) {
            $existingExe = $null
            try { $existingExe = $existingProcess.Path } catch { $existingExe = $null }
            $existingIsAgent = $existingExe -and [string]::Equals($existingExe, $agentExe, [StringComparison]::OrdinalIgnoreCase)
        }
        if ($existingIsAgent) {
            if ($IgnoreAlreadyRunning.IsPresent) {
                Write-Host "Agent already running with PID $existingPid; nothing to do."
                exit 0
            }
            throw "Agent appears to already be running with PID $existingPid. Run Status-Agent.ps1 or Stop-Agent.ps1 first."
        }
        if ($existingProcess) {
            Write-Host "PID file $pidPath points at PID $existingPid which is not this install's agent (reboot pid reuse). Treating as stale and starting."
        }
        Remove-Item -Path $pidPath -Force -ErrorAction SilentlyContinue
    }
}

$startProcessArgs = @{
    FilePath = $agentExe
    WorkingDirectory = (Split-Path -Path $agentExe -Parent)
    WindowStyle = "Hidden"
    PassThru = $true
}

if (-not [string]::IsNullOrWhiteSpace($AgentArguments)) {
    $startProcessArgs.ArgumentList = $AgentArguments
}

$process = Start-Process @startProcessArgs

$process.Id | Set-Content -Path $pidPath -Encoding ASCII

Write-Host "ImageAnywhere Agent started with PID $($process.Id)."
Write-Host "Logon persistence: managed by the install's Register-Startup entry (and the agent self-heals it at start); Unregister-Startup.ps1 opts this user out."
