# Machine-Enforce.ps1 - On-logon enforcer for Standard-Machine shopfloor apps
# (UDC, eDNC, NTLARS, future additions).
#
# Runs under a SYSTEM scheduled task triggered at user logon on Standard-Machine
# PCs only (Timeclock PCs skip registration). Mirrors CMM-Enforce / Acrobat-
# Enforce: mounts the SFLD share, reads machineapps-manifest.json from the
# share, hands off to Install-FromManifest.ps1 which installs anything whose
# detection fails.
#
# Why this exists: Intune DSC's main-category YAML used to handle UDC/eDNC/
# NTLARS enforcement, but DSC has no pc-subtype awareness so Timeclocks in
# category=main got Machine-only apps like UDC pushed to them. These apps
# were pulled from the DSC YAML; this enforcer replaces their drift-correction
# behavior while leaving initial install to the imaging preinstall phase.
#
# Graceful degradation mirrors CMM-Enforce:
#   - SFLD creds missing (Azure DSC has not run yet) -> log + exit 0
#   - Share unreachable (network, VPN)              -> log + exit 0
#   - Install failure on any one app                -> log + continue with next
#
# Never returns non-zero to the task scheduler; failures show up in the log.

$ErrorActionPreference = 'Continue'

$installRoot = 'C:\Program Files\GE\MachineApps'
$libPath     = Join-Path $installRoot 'lib\Install-FromManifest.ps1'
$logDir      = 'C:\Logs\MachineApps'
$logFile     = Join-Path $logDir ('enforce-{0}.log' -f (Get-Date -Format 'yyyyMMdd'))
# Use a drive letter that does not clash with CMM-Enforce (S:) or
# Acrobat-Enforce (T:) so enforcers can run concurrently at logon.
$driveLetter = 'U:'

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 "=== Machine-Enforce session start (PID $PID, user $env:USERNAME) ==="
Write-EnforceLog "================================================================"

# --- Gate: this enforcer is Standard-Machine only. ---
# Belt-and-suspenders: registration is already Machine-only, but double-check
# so a manual copy to a Timeclock PC would no-op instead of chewing through
# the manifest on a device that shouldn't run it.
$subtypeFile = 'C:\Enrollment\pc-subtype.txt'
if (Test-Path $subtypeFile) {
    $sub = (Get-Content $subtypeFile -First 1 -ErrorAction SilentlyContinue).Trim()
    if ($sub -and $sub -ne 'Machine') {
        Write-EnforceLog "pc-subtype is '$sub' (not Machine) - exiting"
        exit 0
    }
}

# --- Load site-config for machineappsSharePath ---
$getProfileScript = 'C:\Enrollment\shopfloor-setup\Shopfloor\lib\Get-PCProfile.ps1'
if (-not (Test-Path $getProfileScript)) {
    Write-EnforceLog "Get-PCProfile.ps1 not found at $getProfileScript - cannot locate share" "ERROR"
    exit 0
}
. $getProfileScript

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

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

# --- SFLD credential lookup (written by Azure DSC post-PPKG). Bail
#     gracefully if the creds haven't been provisioned yet. ---
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 'machineapps-manifest.json'
    if (-not (Test-Path $manifestOnShare)) {
        Write-EnforceLog "machineapps-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 "=== Machine-Enforce session end ==="
}

exit 0
