# Keyence-Enforce.ps1 - On-logon Keyence app enforcer (mini-DSC side).
#
# Runs under a SYSTEM scheduled task triggered at user logon. Mounts the
# tsgwp00525 SFLD share using creds written to HKLM by Azure DSC, reads
# keyence-manifest.json from the share, and hands off to Install-FromManifest.ps1
# which installs anything whose detection fails.
#
# When Keyence ships a VR-6000 update: drop the new MSI (or driver package)
# in the tsgwp00525 share alongside a bumped keyence-manifest.json, and every
# Keyence PC upgrades on its next logon.
#
# Same graceful-degradation pattern as CMM-Enforce: SFLD creds missing, share
# unreachable, or per-app install failure all log and continue. Task never
# returns non-zero so the "last run" UI stays clean; read the log for truth.

$ErrorActionPreference = 'Continue'

$installRoot = 'C:\Program Files\GE\Keyence'
$libPath     = Join-Path $installRoot 'lib\Install-FromManifest.ps1'
$logDir      = 'C:\Logs\Keyence'
$logFile     = Join-Path $logDir ('enforce-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
$driveLetter = 'S:'

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

function Write-EnforceLog {
    param([string]$Message, [string]$Level = 'INFO')
    $line = "[{0}] [{1}] {2}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message
    Write-Host $line
    Add-Content -Path $logFile -Value $line -ErrorAction SilentlyContinue
}

Write-EnforceLog "================================================================"
Write-EnforceLog "=== Keyence-Enforce session start (PID $PID, user $env:USERNAME) ==="
Write-EnforceLog "================================================================"

# --- Load site-config + pcProfile (for keyenceSharePath) ---
# Dot-source the same Get-PCProfile.ps1 used during imaging. It populates
# $pcProfile/$siteConfig script variables from C:\Enrollment\site-config.json.
$getProfileScript = 'C:\Enrollment\shopfloor-setup\Shopfloor\lib\Get-PCProfile.ps1'
if (-not (Test-Path $getProfileScript)) {
    Write-EnforceLog "Get-PCProfile.ps1 not found at $getProfileScript - is this a Keyence PC?" "ERROR"
    exit 0
}
. $getProfileScript

if (-not $pcProfile -or -not $pcProfile.keyenceSharePath) {
    Write-EnforceLog "No keyenceSharePath in profile - nothing to enforce" "WARN"
    exit 0
}

$sharePath = $pcProfile.keyenceSharePath
Write-EnforceLog "Share: $sharePath"

# --- SFLD credential lookup (written by Azure DSC post-PPKG). Bail gracefully
#     if the creds are not yet provisioned; next logon will retry. ---
function Get-SFLDCredential {
    param([string]$ServerName)
    $basePath = 'HKLM:\SOFTWARE\GE\SFLD\Credentials'
    if (-not (Test-Path $basePath)) { return $null }

    foreach ($entry in Get-ChildItem -Path $basePath -ErrorAction SilentlyContinue) {
        $props = Get-ItemProperty -Path $entry.PSPath -ErrorAction SilentlyContinue
        if (-not $props -or -not $props.TargetHost) { continue }
        if ($props.TargetHost -eq $ServerName -or
            $props.TargetHost -like "$ServerName.*" -or
            $ServerName -like "$($props.TargetHost).*") {
            return @{
                Username   = $props.Username
                Password   = $props.Password
                TargetHost = $props.TargetHost
                KeyName    = $entry.PSChildName
            }
        }
    }
    return $null
}

$serverName = ($sharePath -replace '^\\\\', '') -split '\\' | Select-Object -First 1
$cred = Get-SFLDCredential -ServerName $serverName

if (-not $cred -or -not $cred.Username -or -not $cred.Password) {
    Write-EnforceLog "No SFLD credential for $serverName yet (Azure DSC has not provisioned it) - will retry at next logon"
    exit 0
}

Write-EnforceLog "Credential: $($cred.KeyName) (user: $($cred.Username))"

# --- Mount the share ---
net use $driveLetter /delete /y 2>$null | Out-Null

$netResult = & net use $driveLetter $sharePath /user:$($cred.Username) $($cred.Password) /persistent:no 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-EnforceLog "net use failed (exit $LASTEXITCODE): $netResult" "WARN"
    Write-EnforceLog "Share unreachable - probably off-network. Will retry at next logon."
    exit 0
}
Write-EnforceLog "Mounted $sharePath as $driveLetter"

try {
    $manifestOnShare = Join-Path $driveLetter 'keyence-manifest.json'
    if (-not (Test-Path $manifestOnShare)) {
        Write-EnforceLog "keyence-manifest.json not found on share - nothing to enforce" "WARN"
        return
    }

    if (-not (Test-Path $libPath)) {
        Write-EnforceLog "Install-FromManifest.ps1 not found at $libPath" "ERROR"
        return
    }

    Write-EnforceLog "Handing off to Install-FromManifest.ps1 (InstallerRoot=$driveLetter)"
    & $libPath -ManifestPath $manifestOnShare -InstallerRoot $driveLetter -LogFile $logFile
    $rc = $LASTEXITCODE
    Write-EnforceLog "Install-FromManifest returned $rc"
}
finally {
    net use $driveLetter /delete /y 2>$null | Out-Null
    Write-EnforceLog "Unmounted $driveLetter"
    Write-EnforceLog "=== Keyence-Enforce session end ==="
}

# Always return 0 so the scheduled task never shows "last run failed" noise.
exit 0
