#!/usr/bin/env bash
# A-imaging/run.sh - exercise the shopfloor-setup imaging chain on the win11
# VM (Shopfloor baseline + per-PC-type stage scripts), stopping before
# PPKG / Intune handoff. Skips actual binary installs by default; orchestration-
# only test. Path B exercises the per-app installs.
#
# Usage:
#   ./run.sh                       # Standard / Machine
#   ./run.sh CMM                   # CMM (no subtype)
#   ./run.sh Standard Timeclock    # explicit
#
# Env:
#   VM_DOMAIN          override VM name (default win11)
#   SKIP_REVERT=1      skip blank-slate snapshot revert (faster iteration)
#   PREINSTALL_PATH    UNC to a preinstall payload tree (default unset = skip 00-PreInstall installs)

set -euo pipefail

PCTYPE="${1:-Standard}"
PCSUBTYPE="${2:-Machine}"

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$HERE/.." && pwd)"
REPO_ROOT="$(cd "$TEST_ROOT/../../../.." && pwd)"

source "$TEST_ROOT/lib/qga.sh"

if [[ -t 1 ]]; then
    G='\033[32m'; R='\033[31m'; Y='\033[33m'; D='\033[0m'
else
    G=''; R=''; Y=''; D=''
fi

phase() { printf "\n${Y}=== %s ===${D}\n" "$*"; }
ok()    { printf "${G}[ OK ]${D} %s\n" "$*"; }
fail()  { printf "${R}[FAIL]${D} %s\n" "$*"; FAILED=1; }

FAILED=0

phase "A-imaging.run for PCType=$PCTYPE PCSubType=$PCSUBTYPE"

if [[ "${SKIP_REVERT:-}" != "1" ]]; then
    vm_revert_to_blank_slate
else
    log "skipping snapshot revert (SKIP_REVERT=1)"
    vm_start_if_needed
fi

phase "1. stage shopfloor-setup tree on samba share"
# Stage from the live repo into a host-samba-accessible location so the VM
# can robocopy across.
SETUP_STAGE="/home/camp/pxe-images/test-stage-A/shopfloor-setup"
rm -rf "/home/camp/pxe-images/test-stage-A"
mkdir -p "$SETUP_STAGE"
cp -r "$REPO_ROOT/playbook/shopfloor-setup/." "$SETUP_STAGE/"
log "staged $(du -sh "$SETUP_STAGE" | cut -f1) at $SETUP_STAGE"

# Also stage the A-imaging chain runner (the PS1 we just wrote) so the VM
# can invoke it with parameters.
cp "$HERE/stage-image.ps1" "/home/camp/pxe-images/test-stage-A/stage-image.ps1"
# matrix.json + verify-state.ps1 for post-run state check
cp "$TEST_ROOT/matrix.json"       "/home/camp/pxe-images/test-stage-A/matrix.json"
cp "$TEST_ROOT/lib/verify-state.ps1" "/home/camp/pxe-images/test-stage-A/verify-state.ps1"

vm_mount_share

phase "2. run imaging chain on VM"
qga_run_ps <<EOF
\$ErrorActionPreference='Continue'
# Pull stage-image.ps1 + verify-state.ps1 + matrix to local C:\\
New-Item -ItemType Directory -Force -Path 'C:\\Tools\\test-harness' | Out-Null
[System.IO.File]::WriteAllBytes('C:\\Tools\\test-harness\\stage-image.ps1',   [System.IO.File]::ReadAllBytes('Z:\\test-stage-A\\stage-image.ps1'))
[System.IO.File]::WriteAllBytes('C:\\Tools\\test-harness\\verify-state.ps1',  [System.IO.File]::ReadAllBytes('Z:\\test-stage-A\\verify-state.ps1'))
[System.IO.File]::WriteAllBytes('C:\\Tools\\test-harness\\matrix.json',       [System.IO.File]::ReadAllBytes('Z:\\test-stage-A\\matrix.json'))

# Run the chain - SetupSrcPath points at the host samba mirror so the runner
# robocopies it onto C:\\Enrollment\\shopfloor-setup.
& C:\\Tools\\test-harness\\stage-image.ps1 -PCType '$PCTYPE' -PCSubType '$PCSUBTYPE' -SetupSrcPath 'Z:\\test-stage-A\\shopfloor-setup' ${PREINSTALL_PATH:+-PreInstallSrcPath '$PREINSTALL_PATH'}
EOF
RUN_RC=$?

if [[ $RUN_RC -eq 0 ]]; then
    ok "stage chain returned exit 0"
else
    fail "stage chain returned exit $RUN_RC"
fi

phase "3. collect transcripts"
qga_run_ps <<'EOF' || true
"--- C:\Logs\SFLD ---"
Get-ChildItem C:\Logs\SFLD -ErrorAction SilentlyContinue | Select-Object Name,Length,LastWriteTime
"--- C:\Logs\PreInstall ---"
Get-ChildItem C:\Logs\PreInstall -ErrorAction SilentlyContinue | Select-Object Name,Length,LastWriteTime
"--- ran stage scripts (last 60 lines per transcript) ---"
foreach ($f in Get-ChildItem C:\Logs\SFLD -Filter '*.log' -ErrorAction SilentlyContinue) {
    "=== $($f.FullName) ==="
    Get-Content $f.FullName -Tail 30
}
EOF

phase "result"
if [[ $FAILED -eq 0 ]]; then
    ok "A-imaging: chain completed for $PCTYPE/$PCSUBTYPE"
    exit 0
else
    fail "A-imaging: chain had failures for $PCTYPE/$PCSUBTYPE"
    exit 1
fi
