# 09-Setup-Keyence.ps1 - Keyence type setup (runs during shopfloor-setup phase).
#
# Performs the imaging-time install of Keyence VR-6000 Series Software MSI +
# KEYENCE VR Series USB driver from the staged bundle. Ongoing enforcement
# is handled by GE-Enforce (registered separately in Run-ShopfloorSetup.ps1)
# reading keyence/manifest.json from the tsgwp00525 share.
#
# Layout at $PSScriptRoot (xcopied by startnet.cmd only for PCTYPE=Keyence):
#   keyence-manifest.json
#   09-Setup-Keyence.ps1   (this file)
#   installers\VR-6000 Series Software.msi
#   drivers\keyence_vr_series.inf (+ cat + amd64\{Wdf,WinUsb}CoInstaller*.dll)
#
# Library lookup: the imaging-time install uses the common Install-FromManifest
# library at ..\common\lib\Install-FromManifest.ps1 (relative to $PSScriptRoot).
#
# Log: C:\Logs\Keyence\09-Setup-Keyence.log
#      C:\Logs\Keyence\install.log   (written by Install-FromManifest)

$ErrorActionPreference = 'Continue'

$manifestPath   = Join-Path $PSScriptRoot 'keyence-manifest.json'
$libSource      = Join-Path $PSScriptRoot '..\common\lib\Install-FromManifest.ps1'

$logDir         = 'C:\Logs\Keyence'
$installLog     = Join-Path $logDir 'install.log'
$transcriptLog  = Join-Path $logDir '09-Setup-Keyence.log'

if (-not (Test-Path $logDir)) {
    New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}

try { Start-Transcript -Path $transcriptLog -Append -Force | Out-Null } catch {}

function Write-KeyenceLog {
    param([string]$Message, [string]$Level = 'INFO')
    $stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Write-Host "[$stamp] [$Level] $Message"
}

Write-KeyenceLog "================================================================"
Write-KeyenceLog "=== Keyence Setup (imaging-time) session start (PID $PID) ==="
Write-KeyenceLog "Running as: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"
Write-KeyenceLog "Script root: $PSScriptRoot"
Write-KeyenceLog "================================================================"

# Status push to PXE webapp - best-effort, never blocks imaging.
$pxeStatusLib = Join-Path $PSScriptRoot '..\Shopfloor\lib\Send-PxeStatus.ps1'
if (Test-Path $pxeStatusLib) {
    try { . $pxeStatusLib; Send-PxeStatus -Stage '09-Setup-Keyence: starting' -StageIndex 3 -StageTotal 8 } catch { }
}

# Diagnostic dump
foreach ($file in @('pc-type.txt','pc-subtype.txt','machine-number.txt')) {
    $path = "C:\Enrollment\$file"
    if (Test-Path -LiteralPath $path) {
        $content = (Get-Content -LiteralPath $path -First 1 -ErrorAction SilentlyContinue).Trim()
        Write-KeyenceLog "  $file = $content"
    } else {
        Write-KeyenceLog "  $file = (not present)"
    }
}

# ============================================================================
# Step 0: Pre-stage Keyence VR Series USB driver + trust the publisher cert.
# ============================================================================
# The VR-6000 MSI invokes dpinst.exe internally as a custom action to install
# the USB driver. dpinst inherits the MSI's silent context inconsistently and
# usually pops a Setup-wizard GUI even with /qn on the parent MSI.
#
# Two pre-steps suppress the prompt:
#   1. pnputil /add-driver /install stages the INF + co-installers into the
#      Windows DriverStore. dpinst then sees the driver as already present and
#      skips its install path (the GUI lives behind the "needs to install"
#      branch).
#   2. Add the publisher cert (extracted from the catalog file) to
#      LocalMachine\TrustedPublisher so dpinst's "Would you like to install
#      this device software?" Windows Security dialog auto-accepts.
#
# If either step fails, log + continue - the MSI is still expected to install
# successfully; the only fallout is the GUI prompt the operator would have
# had to click through anyway.
$driverInf = Join-Path $PSScriptRoot 'drivers\keyence_vr_series.inf'
$driverCat = Join-Path $PSScriptRoot 'drivers\KEYENCE_VR_SERIES.cat'

if (Test-Path -LiteralPath $driverInf) {
    Write-KeyenceLog "Pre-staging USB driver via pnputil (suppresses dpinst GUI inside MSI)"
    try {
        $pnpOut = & pnputil /add-driver $driverInf /install 2>&1
        Write-KeyenceLog "  pnputil exit $LASTEXITCODE"
        foreach ($line in ($pnpOut | Where-Object { $_ })) { Write-KeyenceLog "    $line" }
    } catch {
        Write-KeyenceLog "  pnputil failed: $_" 'WARN'
    }
} else {
    Write-KeyenceLog "Driver INF not found at $driverInf - skipping pre-stage" 'WARN'
}

if (Test-Path -LiteralPath $driverCat) {
    Write-KeyenceLog "Adding Keyence publisher cert to LocalMachine\TrustedPublisher store"
    try {
        $sig = Get-AuthenticodeSignature -FilePath $driverCat -ErrorAction Stop
        if ($sig -and $sig.SignerCertificate) {
            $store = New-Object System.Security.Cryptography.X509Certificates.X509Store('TrustedPublisher','LocalMachine')
            $store.Open('ReadWrite')
            $store.Add($sig.SignerCertificate)
            $store.Close()
            Write-KeyenceLog "  Added: $($sig.SignerCertificate.Subject) thumb=$($sig.SignerCertificate.Thumbprint)"
        } else {
            Write-KeyenceLog "  Catalog is not signed - cert pre-trust skipped" 'WARN'
        }
    } catch {
        Write-KeyenceLog "  Cert add failed: $_" 'WARN'
    }
} else {
    Write-KeyenceLog "Driver catalog not found at $driverCat - cert pre-trust skipped" 'WARN'
}

# ============================================================================
# Step 1: Install via manifest (imaging-time)
# ============================================================================
if (-not (Test-Path $manifestPath)) {
    Write-KeyenceLog "keyence-manifest.json not found at $manifestPath" "ERROR"
} elseif (-not (Test-Path $libSource)) {
    Write-KeyenceLog "Install-FromManifest.ps1 not found at $libSource" "ERROR"
} else {
    Write-KeyenceLog "Running Install-FromManifest (InstallerRoot=$PSScriptRoot)"
    & $libSource -ManifestPath $manifestPath -InstallerRoot $PSScriptRoot -LogFile $installLog
    $rc = $LASTEXITCODE
    Write-KeyenceLog "Install-FromManifest returned $rc"
}

# ============================================================================
# Step 1.5: Install Keyence-bundled DirectX End-User Runtimes
# ============================================================================
# VR-6000's MSI deploys DXSETUP.exe to the install dir but never runs it.
# Without DirectX, the app's first launch errors: "Runtime required to move
# the application is not installed correctly. Install from the following
# folder: C:\Program Files\Keyence\VR-6000\Common\DirectX End-User Runtimes\
# DXSETUP.exe". Run it silently here; /silent suppresses all UI + reboot.
$dxSetup = 'C:\Program Files\KEYENCE\VR-6000\Common\DirectX End-User Runtimes\DXSETUP.exe'
$dxSetupAlt = 'C:\Program Files (x86)\KEYENCE\VR-6000\Common\DirectX End-User Runtimes\DXSETUP.exe'
if (Test-Path -LiteralPath $dxSetup)    { $dxPath = $dxSetup }
elseif (Test-Path -LiteralPath $dxSetupAlt) { $dxPath = $dxSetupAlt }
else { $dxPath = $null }

if ($dxPath) {
    Write-KeyenceLog "Running DirectX End-User Runtimes: $dxPath /silent"
    try {
        $p = Start-Process -FilePath $dxPath -ArgumentList '/silent' -Wait -PassThru -NoNewWindow
        Write-KeyenceLog "  DXSETUP exit $($p.ExitCode)"
    } catch {
        Write-KeyenceLog "  DXSETUP failed: $_" 'WARN'
    }
} else {
    Write-KeyenceLog "DXSETUP.exe not found under either Program Files - DirectX install skipped" 'WARN'
}

# ============================================================================
# Step 2: OpenText auto-start at login (HostExplorer "WJ Shopfloor" session)
# ============================================================================
$autoStartLib = Join-Path $PSScriptRoot '..\Shopfloor\lib\Set-OpenTextAutoStart.ps1'
if (Test-Path -LiteralPath $autoStartLib) {
    Write-KeyenceLog "Calling $autoStartLib"
    & $autoStartLib
} else {
    Write-KeyenceLog "Set-OpenTextAutoStart.ps1 not found at $autoStartLib - OpenText auto-start NOT configured" 'WARN'
}

if (Get-Command Send-PxeStatus -ErrorAction SilentlyContinue) {
    $finalStatus = if ($rc -eq 0) { 'in_progress' } else { 'failed' }
    $finalErr    = if ($rc -ne 0) { "Install-FromManifest exit $rc" } else { '' }
    Send-PxeStatus -Stage '09-Setup-Keyence: complete' -StageIndex 4 -StageTotal 8 -Status $finalStatus -Error_ $finalErr
}

Write-KeyenceLog "================================================================"
Write-KeyenceLog "=== Keyence Setup session end ==="
Write-KeyenceLog "================================================================"

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