# 09-Setup-Keyence.ps1 - Keyence type setup (runs during shopfloor-setup phase).
#
# Performs one-shot imaging-time install and then registers the ongoing
# enforcer. Mirrors CMM's pattern.
#
# Sequence:
#   1. Run Install-FromManifest against the staged bundle in $PSScriptRoot.
#      Installs VR-6000 Series Software MSI + KEYENCE VR Series USB driver.
#   2. Stage Install-FromManifest.ps1 + Keyence-Enforce.ps1 + keyence-manifest.json
#      to C:\Program Files\GE\Keyence so the scheduled task has them post-imaging.
#   3. Register "GE Keyence Enforce" scheduled task (SYSTEM, logon trigger).
#      It mounts the tsgwp00525 share, reads the manifest there, and upgrades
#      anything whose detection falls out of sync. Credentials for the share
#      arrive via Azure DSC writing to HKLM:\SOFTWARE\GE\SFLD\Credentials.
#
# Layout at $PSScriptRoot (xcopied by startnet.cmd only for PCTYPE=Keyence):
#   keyence-manifest.json
#   09-Setup-Keyence.ps1   (this file)
#   Keyence-Enforce.ps1    (staged to C:\Program Files\GE\Keyence)
#   lib\Install-FromManifest.ps1   (staged alongside)
#   installers\VR-6000 Series Software.msi
#   drivers\keyence_vr_series.inf (+ cat + amd64\{Wdf,WinUsb}CoInstaller*.dll)
#
# 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 'lib\Install-FromManifest.ps1'
$enforceSource  = Join-Path $PSScriptRoot 'Keyence-Enforce.ps1'

$runtimeRoot    = 'C:\Program Files\GE\Keyence'
$runtimeLibDir  = Join-Path $runtimeRoot 'lib'
$runtimeLib     = Join-Path $runtimeLibDir 'Install-FromManifest.ps1'
$runtimeEnforce = Join-Path $runtimeRoot 'Keyence-Enforce.ps1'
$runtimeManifest= Join-Path $runtimeRoot 'keyence-manifest.json'

$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 "================================================================"

# 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 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 2: Stage runtime scripts to C:\Program Files\GE\Keyence
# ============================================================================
# These survive past any bootstrap cleanup so the logon-triggered scheduled
# task can run them. The manifest is staged too as a fallback for the first
# logon if the share is unreachable.
Write-KeyenceLog "Staging runtime scripts to $runtimeRoot"
foreach ($dir in @($runtimeRoot, $runtimeLibDir)) {
    if (-not (Test-Path $dir)) {
        New-Item -Path $dir -ItemType Directory -Force | Out-Null
    }
}
Copy-Item -Path $libSource     -Destination $runtimeLib      -Force
Copy-Item -Path $enforceSource -Destination $runtimeEnforce  -Force
Copy-Item -Path $manifestPath  -Destination $runtimeManifest -Force

# ============================================================================
# Step 3: Register "GE Keyence Enforce" scheduled task (logon trigger, SYSTEM)
# ============================================================================
$taskName = 'GE Keyence Enforce'

# Drop any stale version first so re-imaging is idempotent.
$existing = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($existing) {
    Write-KeyenceLog "Removing existing scheduled task '$taskName'"
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}

Write-KeyenceLog "Registering scheduled task '$taskName' (logon trigger, SYSTEM)"
try {
    $action    = New-ScheduledTaskAction `
        -Execute 'powershell.exe' `
        -Argument "-NoProfile -ExecutionPolicy Bypass -File `"$runtimeEnforce`""

    $trigger   = New-ScheduledTaskTrigger -AtLogOn
    $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
    $settings  = New-ScheduledTaskSettingsSet `
        -AllowStartIfOnBatteries `
        -DontStopIfGoingOnBatteries `
        -StartWhenAvailable `
        -ExecutionTimeLimit (New-TimeSpan -Hours 1) `
        -MultipleInstances IgnoreNew

    Register-ScheduledTask `
        -TaskName $taskName `
        -Action $action `
        -Trigger $trigger `
        -Principal $principal `
        -Settings $settings `
        -Description 'GE Keyence: enforce VR-6000 Series Software + USB driver against tsgwp00525 SFLD share on user logon' | Out-Null

    Write-KeyenceLog "Scheduled task registered"
} catch {
    Write-KeyenceLog "Failed to register scheduled task: $_" "ERROR"
}

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

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