param(
    [string]$InstallDirectory = (Join-Path $env:LOCALAPPDATA "Programs\ImageAnywhereAgent"),
    [switch]$Force,
    # 2026-07-28 field lesson (two machines in one day): an agent without logon
    # persistence silently dies on every reboot and the fleet loses its safety
    # net. Startup registration is now the DEFAULT (owner-approved 2026-07-28);
    # this switch opts out for lab/temporary installs.
    [switch]$NoStartupRegistration
)

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

$packageRoot = Split-Path -Path $PSScriptRoot -Parent
$agentSource = Join-Path $packageRoot "agent"
if (-not (Test-Path -Path (Join-Path $agentSource "IAUWP.Agent.exe"))) {
    throw "This script must be run from an extracted ImageAnywhere Agent field package."
}

$resolvedInstallDirectory = $InstallDirectory
if (Test-Path -Path $resolvedInstallDirectory) {
    if (-not $Force.IsPresent) {
        throw "Install directory '$resolvedInstallDirectory' already exists. Re-run with -Force to replace package files."
    }
}
else {
    New-Item -ItemType Directory -Path $resolvedInstallDirectory -Force | Out-Null
}

Copy-Item -Path (Join-Path $packageRoot "*") -Destination $resolvedInstallDirectory -Recurse -Force

$startupConfigured = $false
if (-not $NoStartupRegistration.IsPresent) {
    $registerScript = Join-Path $resolvedInstallDirectory "scripts\Register-Startup.ps1"
    if (Test-Path -Path $registerScript) {
        & powershell -NoProfile -ExecutionPolicy Bypass -File $registerScript -InstallDirectory $resolvedInstallDirectory
        $startupConfigured = $true
    }
}

$installRecord = [pscustomobject]@{
    InstalledAt = (Get-Date).ToString("O")
    InstallDirectory = $resolvedInstallDirectory
    AgentExe = Join-Path $resolvedInstallDirectory "agent\IAUWP.Agent.exe"
    StartupConfigured = $startupConfigured
    Notes = if ($startupConfigured) { "Per-user install. A per-user logon Run entry starts the agent at sign-in (remove with scripts\Unregister-Startup.ps1 or Remove-Agent.ps1)." } else { "Per-user install only. Startup registration was skipped (-NoStartupRegistration); the agent runs only when started by hand." }
}
$installRecord | ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $resolvedInstallDirectory "install-location.json") -Encoding UTF8

Write-Host "ImageAnywhere Agent package installed to $resolvedInstallDirectory"
if ($startupConfigured) {
    Write-Host "Startup registered: the agent starts automatically at user sign-in."
}
else {
    Write-Host "No startup behavior was configured (-NoStartupRegistration)."
}
Write-Host "The agent is not running yet for THIS session. Run scripts\Start-Agent.ps1 to start it now."
