# 03-RestoreEDncConfig.ps1 - Restore per-machine eDNC config from .reg backup.
#
# Runs at shopfloor-setup time AFTER 01-eDNC.ps1 has installed eDNC. If the
# tech typed a real machine number at the PXE menu (not left blank -> 9999),
# look for a .reg backup matching that number on the PXE-local copy of the
# setup tree and import it. That restores everything eDNC-side the backup
# captured: eFocas IP/port, PPDCS serial (baud/parity/bits), Hssb KRelay1,
# etc. - instead of the reimaged PC coming up on factory defaults.
#
# After reg import, the tech-typed machine number is written to HKLM and to
# UDC's settings JSON to guarantee the current number wins over whatever the
# backup happened to contain (off-by-one backups exist in the historical
# dump; see ntlars-fixed/ work on the PXE host).
#
# Skipped when:
#   - pc-subtype != Machine (Timeclock PCs do not use a machine number)
#   - machine-number.txt missing / empty / 9999 (tech declined to set one)
#   - ntlars-backups/ folder missing from the staged setup tree
#   - no matching .reg file on disk for this machine number

$ErrorActionPreference = 'Continue'

$logDir = 'C:\Logs\SFLD'
if (-not (Test-Path $logDir)) { try { New-Item -ItemType Directory -Path $logDir -Force | Out-Null } catch {} }
try { Start-Transcript -Path (Join-Path $logDir '03-RestoreEDncConfig.log') -Append -Force | Out-Null } catch {}

Write-Host "=== Restore eDNC config from backup ==="

# ---- Sub-type gate ----
$subtypeFile = 'C:\Enrollment\pc-subtype.txt'
if (Test-Path $subtypeFile) {
    $subtype = (Get-Content $subtypeFile -First 1 -ErrorAction SilentlyContinue).Trim()
    if ($subtype -eq 'Timeclock') {
        Write-Host "Standard-Timeclock - skipping."
        try { Stop-Transcript | Out-Null } catch {}
        return
    }
}

# ---- Read machine number captured at PXE time ----
$mnFile = 'C:\Enrollment\machine-number.txt'
if (-not (Test-Path $mnFile)) {
    Write-Host "machine-number.txt not present - skipping (tech did not set one)."
    try { Stop-Transcript | Out-Null } catch {}
    return
}
$machineNum = (Get-Content $mnFile -First 1 -ErrorAction SilentlyContinue).Trim()
if (-not $machineNum -or $machineNum -eq '9999') {
    Write-Host "Machine number is '$machineNum' (placeholder or empty) - skipping."
    try { Stop-Transcript | Out-Null } catch {}
    return
}

Write-Host "Machine number: $machineNum"

# ---- Locate local backup root (staged from PXE during imaging) ----
$backupRoot = 'C:\Enrollment\shopfloor-setup\Standard\ntlars-backups'
if (-not (Test-Path $backupRoot)) {
    Write-Host "ntlars-backups folder not staged at $backupRoot - skipping."
    try { Stop-Transcript | Out-Null } catch {}
    return
}

. "$PSScriptRoot\..\Shopfloor\lib\Restore-EDncReg.ps1"
$imported = Import-EDncRegBackup -SourceRoot $backupRoot -MachineNumber $machineNum

if (-not $imported) {
    Write-Host "No backup imported - leaving eDNC at installer defaults."
    try { Stop-Transcript | Out-Null } catch {}
    return
}

# ---- Tech-typed number wins: overwrite MachineNo in both eDNC and UDC. ----
# The imported .reg probably already has the right number (we rewrote the
# historical dump) but off-by-one backups exist, and this is cheap insurance.
. "$PSScriptRoot\..\Shopfloor\lib\Update-MachineNumber.ps1"

$current = Get-CurrentMachineNumber
Write-Host "Post-import state: UDC='$($current.Udc)' eDNC='$($current.Ednc)'"

$result = Update-MachineNumber -NewNumber $machineNum
if ($result.UdcUpdated)  { Write-Host "  UDC MachineNumber set to $machineNum" }
if ($result.EdncUpdated) { Write-Host "  eDNC MachineNo set to $machineNum" }
foreach ($err in $result.Errors) { Write-Warning "  $err" }

try { Stop-Transcript | Out-Null } catch {}
