<#
.SYNOPSIS
    One-step endpoint evidence runner for the SiteKings legacy Windows lane.

    PowerShell 2/3 friendly. Run this from the extracted lab kit on a Windows 7
    SP1 or Windows Server 2008 R2 lab endpoint after install, tray, watchdog,
    and peer-healing checks are ready to capture.
#>

param(
    [string]$InstallDir = "",
    [string]$OutDir = "",
    [switch]$ExerciseSelfRescue,
    [switch]$ExercisePeerRecover,
    [string]$ApiKey = ""
)

$ErrorActionPreference = "SilentlyContinue"
$ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path

function Resolve-InstallDir {
    if (-not [string]::IsNullOrEmpty($InstallDir)) { return $InstallDir }
    foreach ($candidate in @("$env:ProgramData\SiteKings", "$env:ProgramData\LCL")) {
        if (Test-Path $candidate) { return $candidate }
    }
    return "$env:ProgramData\SiteKings"
}

function Write-TextFile {
    param(
        [string]$Path,
        [string[]]$Lines
    )
    [IO.File]::WriteAllText($Path, (($Lines -join "`r`n") + "`r`n"))
}

function Escape-JsonString {
    param([string]$Value)
    if ($null -eq $Value) { return "" }
    $s = [string]$Value
    $s = $s.Replace("\", "\\")
    $s = $s.Replace('"', '\"')
    $s = $s.Replace("`r", "\r")
    $s = $s.Replace("`n", "\n")
    $s = $s.Replace("`t", "\t")
    return $s
}

function Write-OperatorContext {
    param([string]$Path)
    $username = ""
    $isElevated = $false
    try {
        $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
        $username = $identity.Name
        $principal = New-Object Security.Principal.WindowsPrincipal($identity)
        $isElevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    } catch { }

    $elevatedLiteral = if ($isElevated) { "true" } else { "false" }
    $lines = @(
        "{",
        '  "schema": "legacy-windows-lab-operator-context",',
        '  "is_elevated": ' + $elevatedLiteral + ",",
        '  "username": "' + (Escape-JsonString $username) + '",',
        '  "computer_name": "' + (Escape-JsonString $env:COMPUTERNAME) + '",',
        '  "script_root": "' + (Escape-JsonString $ScriptRoot) + '"',
        "}"
    )
    Write-TextFile $Path $lines
}

function Resolve-LocalScript {
    param(
        [string]$Name,
        [string]$InstallRoot
    )
    foreach ($candidate in @(
        (Join-Path $ScriptRoot $Name),
        (Join-Path $InstallRoot $Name),
        (Join-Path (Join-Path $ScriptRoot "client") $Name)
    )) {
        if (Test-Path $candidate) { return $candidate }
    }
    return ""
}

$InstallRoot = Resolve-InstallDir
$CollectScript = Resolve-LocalScript "legacy-windows-lab-collect.ps1" $InstallRoot
if ([string]::IsNullOrEmpty($CollectScript)) {
    Write-Host "legacy-windows-lab-run failed: legacy-windows-lab-collect.ps1 not found"
    exit 2
}

if ([string]::IsNullOrEmpty($OutDir)) {
    $stamp = Get-Date -Format "yyyyMMdd-HHmmss"
    $OutDir = Join-Path (Join-Path $InstallRoot "logs") ("legacy-windows-lab-evidence-" + $stamp)
}
if (-not (Test-Path $OutDir)) {
    New-Item -ItemType Directory -Path $OutDir -Force | Out-Null
}

$operatorContext = Join-Path $OutDir "operator-context.json"
Write-OperatorContext $operatorContext

$collectArgs = @(
    "-NoProfile",
    "-ExecutionPolicy",
    "Bypass",
    "-File",
    $CollectScript,
    "-InstallDir",
    $InstallRoot,
    "-OutDir",
    $OutDir
)
if ($ExerciseSelfRescue) { $collectArgs += "-ExerciseSelfRescue" }
if ($ExercisePeerRecover) { $collectArgs += "-ExercisePeerRecover" }
if (-not [string]::IsNullOrEmpty($ApiKey)) {
    $collectArgs += "-ApiKey"
    $collectArgs += $ApiKey
}

$collectOut = & powershell.exe $collectArgs 2>&1 | Out-String
$runnerLog = Join-Path $OutDir "legacy-windows-lab-run-output.txt"
[IO.File]::WriteAllText($runnerLog, $collectOut)
$collectExit = $LASTEXITCODE

$nextSteps = Join-Path $OutDir "LEGACY-LAB-NEXT-STEPS.txt"
Write-TextFile $nextSteps @(
    "legacy-windows-lab-run complete",
    "",
    "Endpoint lane: Windows 7 SP1 / Windows Server 2008 R2 first-iteration evidence",
    "Evidence folder: $OutDir",
    "Collector manifest: legacy-windows-lab-collector-manifest.json",
    "Smoke JSON: legacy-windows-lab-smoke.json",
    "",
    "Copy this entire evidence folder back to Mac-Studio 10.0.10.41.",
    "",
    "On Mac-Studio, validate and bundle the folder:",
    "scripts/legacy-windows-lab-intake.py --collect-root <this-folder> --build-manifest bin/legacy-windows-first-iteration-build-manifest.json --output-dir retained-legacy-windows-evidence",
    "",
    "After both lab platform folders are copied back, run the two-platform finalizer:",
    "scripts/legacy-windows-first-iteration-finalize.py --win7-collect-root <win7-evidence-folder> --server-2008-r2-collect-root <server-2008-r2-evidence-folder> --build-manifest bin/legacy-windows-first-iteration-build-manifest.json --output-dir retained-legacy-windows-evidence",
    "",
    "Retain the final readiness proof:",
    "retained-legacy-windows-evidence\legacy-windows-first-iteration-final-summary.json",
    "retained-legacy-windows-evidence\legacy-windows-first-iteration-final-summary.json.sha256",
    "After finalization, verify the final summary hash sidecar before customer pilot approval.",
    "",
    "If intake needs manual troubleshooting, validate directly. Choose the command for this platform:",
    "",
    "Windows Server 2008 R2 SP1 evidence-only validation:",
    "scripts/legacy-windows-lab-evidence-check.py legacy-windows-lab-smoke.json --collect-manifest legacy-windows-lab-collector-manifest.json --collect-root <this-folder> --require-self-rescue",
    "Do not add --require-win10-status on Server 2008 R2.",
    "Do not pass --win10-upgrade-status or --win10-upgrade-log for Server 2008 R2.",
    "",
    "Windows 7 SP1 only, after the Windows 10 probe and bridge artifacts exist:",
    "scripts/legacy-windows-lab-evidence-check.py legacy-windows-lab-smoke.json --collect-manifest legacy-windows-lab-collector-manifest.json --collect-root <this-folder> --require-self-rescue --require-win10-status",
    "",
    "Then create a retained evidence ZIP directly. Choose the command for this platform:",
    "",
    "Server 2008 R2 direct evidence ZIP command:",
    "scripts/legacy-windows-first-iteration-evidence-bundle.py --hostname <host> --output legacy-windows-<host>-evidence.zip --lab-smoke legacy-windows-lab-smoke.json --collect-manifest legacy-windows-lab-collector-manifest.json --collect-root <this-folder> --build-manifest bin/legacy-windows-first-iteration-build-manifest.json",
    "",
    "Windows 7 SP1 direct bridge ZIP command:",
    "scripts/legacy-windows-first-iteration-evidence-bundle.py --hostname <host> --output legacy-windows-<host>-evidence.zip --lab-smoke legacy-windows-lab-smoke.json --collect-manifest legacy-windows-lab-collector-manifest.json --collect-root <this-folder> --build-manifest bin/legacy-windows-first-iteration-build-manifest.json --win10-upgrade-status win10_upgrade.status.json --win10-upgrade-log win10_upgrade.log",
    "",
    "After both platforms are bundled, run:",
    "scripts/legacy-windows-first-iteration-readiness.py legacy-windows-WIN7-LAB-evidence.zip legacy-windows-SRV2008R2-LAB-evidence.zip",
    "",
    "Windows 7 SP1 bridge artifacts, when available: win10_upgrade.status.json and win10_upgrade.log",
    "Windows Server 2008 R2 is evidence-only for this first iteration; do not run the Windows 10 bridge there."
)

Write-Host ("legacy-windows-lab-run wrote evidence to " + $OutDir)
Write-Host ("Next steps: " + $nextSteps)
if ($collectExit -ne 0) {
    Write-Host ("Collector exit code: " + $collectExit)
    exit $collectExit
}
exit 0
