# A-imaging/stage-image.ps1 - run the imaging chain on the VM, stop before
# PPKG / Intune. Mimics what Run-ShopfloorSetup does up to the per-PC-type
# stage scripts; skips:
#   - PPKG install (changes machine identity, rebooty)
#   - sync_intune registration (Azure-bound)
#   - final reboot
#
# Verifies the chain integrity (script ordering, PCTypes filter logic,
# transcripts written, expected stage scripts present per type) without
# touching real machine identity or burning a real provisioning cycle.
#
# Real binary installers (Oracle / VC++ / OpenText / UDC) live on the
# live PXE share, not in this repo, so 00-PreInstall-MachineApps.ps1 will
# log "Installer file not found" for every entry it tries to install.
# That is expected for orchestration-only testing - Path B covers actual
# install verification per app.

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)] [string]$PCType,
    [string]$PCSubType = '',
    [Parameter(Mandatory=$true)] [string]$SetupSrcPath,    # UNC to repo's playbook/shopfloor-setup, e.g. \\host\share\shopfloor-setup
    [string]$PreInstallSrcPath = ''                         # optional UNC to a preinstall payload tree; if missing we skip 00-PreInstall
)

$ErrorActionPreference = 'Continue'

function Log { param([string]$m) Write-Host "[$(Get-Date -Format HH:mm:ss)] $m" }

Log "=== A-imaging: stage chain for PCType=$PCType PCSubType=$PCSubType ==="

# --- Clean prior test state ---
Get-Process powershell -ErrorAction SilentlyContinue | Where-Object { $_.Id -ne $PID } | Stop-Process -Force -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force 'C:\Enrollment'   -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force 'C:\Logs\SFLD'    -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force 'C:\Logs\PreInstall' -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force 'C:\PreInstall'   -ErrorAction SilentlyContinue

# --- Stage shopfloor-setup tree ---
Log "copying $SetupSrcPath -> C:\Enrollment\shopfloor-setup"
New-Item -ItemType Directory -Force -Path 'C:\Enrollment\shopfloor-setup' | Out-Null
robocopy $SetupSrcPath 'C:\Enrollment\shopfloor-setup' /E /R:2 /W:2 /NFL /NDL /NJH /NJS /NC /NS | Out-Null

# --- Drop pc-type / pc-subtype / site-config ---
$PCType    | Set-Content -Path 'C:\Enrollment\pc-type.txt'    -Encoding ascii
$PCSubType | Set-Content -Path 'C:\Enrollment\pc-subtype.txt' -Encoding ascii
@{
    siteName            = 'WJ (A-imaging test)'
    shopfloorShareRoot  = '\\192.168.122.1\pxe-images\tsgwp00525-v2\shared\dt\shopfloor'
    common              = @{ commonAppsSharePath = '\\192.168.122.1\pxe-images\tsgwp00525-v2\shared\dt\shopfloor\common\apps' }
} | ConvertTo-Json -Depth 5 | Set-Content -Path 'C:\Enrollment\site-config.json' -Encoding ascii

# --- Stage PreInstall payload if provided ---
if ($PreInstallSrcPath -and (Test-Path $PreInstallSrcPath)) {
    Log "copying $PreInstallSrcPath -> C:\PreInstall"
    New-Item -ItemType Directory -Force -Path 'C:\PreInstall' | Out-Null
    robocopy $PreInstallSrcPath 'C:\PreInstall' /E /R:2 /W:2 /NFL /NDL /NJH /NJS /NC /NS | Out-Null
} else {
    Log "no PreInstall payload provided - 00-PreInstall step will skip"
}

# --- Run stage scripts in order: Shopfloor baseline first, then per-PC-type ---
$setupDir = 'C:\Enrollment\shopfloor-setup'
$stageRan = @()

function Run-StageScripts {
    param([string]$Dir)
    if (-not (Test-Path $Dir)) { return }
    $scripts = Get-ChildItem $Dir -Filter '*.ps1' -File -ErrorAction SilentlyContinue |
               Where-Object { $_.Name -match '^[0-9]{2}-' } |
               Sort-Object Name
    foreach ($s in $scripts) {
        Log "==> $($s.FullName)"
        $rc = 0
        & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $s.FullName 2>&1 | ForEach-Object { Write-Host "    $_" }
        if ($LASTEXITCODE) { $rc = $LASTEXITCODE }
        Log "    exit $rc"
        $script:stageRan += [pscustomobject]@{ Path = $s.FullName; ExitCode = $rc }
    }
}

# 1. Shopfloor baseline scripts (run for every PC type, including Standard)
Run-StageScripts (Join-Path $setupDir 'Shopfloor')

# 2. Per-PC-type stage scripts. Standard / CMM / Keyence / etc each have their
#    own subdir with numbered scripts. Skip "Shopfloor" since that's PCType==Shopfloor.
if ($PCType -ne 'Shopfloor') {
    $typeDir = Join-Path $setupDir $PCType
    Run-StageScripts $typeDir
}

# --- Summary ---
Log "=== chain summary ==="
foreach ($r in $stageRan) {
    $tag = if ($r.ExitCode -eq 0) { '[ OK ]' } else { '[FAIL]' }
    Log "  $tag rc=$($r.ExitCode)  $($r.Path)"
}

$failedCount = ($stageRan | Where-Object { $_.ExitCode -ne 0 }).Count
$totalCount  = $stageRan.Count
Log "=== A-imaging summary: $($totalCount - $failedCount)/$totalCount stage scripts exited 0 ==="
if ($failedCount -gt 0) { exit 1 }
exit 0
