# CMM-Enforce.ps1 - On-logon CMM app enforcer (the 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
# cmm-manifest.json from the share, and hands off to Install-FromManifest.ps1
# which installs anything whose detection fails.
#
# Why logon trigger: shopfloor operators log in at shift start; the PC may
# have been off or DSC may not have provisioned the SFLD creds until the
# Intune side ran post-PPKG. Logon is a natural catch-up point. Once detection
# passes for every app, each run is ~seconds of no-ops.
#
# Why SYSTEM: installers need machine-wide rights and registry access. The
# task is triggered by logon but runs outside the user's session.
#
# Graceful degradation:
#   - SFLD creds missing (Azure DSC hasn't run yet) -> log + exit 0
#   - Share unreachable (network, VPN) -> log + exit 0
#   - Install failure on any one app -> log + continue with the rest
#
# Never returns non-zero to the task scheduler; failures show up in the log.

$ErrorActionPreference = 'Continue'

$installRoot = 'C:\Program Files\GE\CMM'
$libPath     = Join-Path $installRoot 'lib\Install-FromManifest.ps1'
$logDir      = 'C:\Logs\CMM'
$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 "=== CMM-Enforce session start (PID $PID, user $env:USERNAME) ==="
Write-EnforceLog "================================================================"

# --- Load site-config + pcProfile (for cmmSharePath) ---
# Dot-source the same Get-PCProfile.ps1 used during imaging. It walks
# C:\Enrollment\site-config.json into $pcProfile/$siteConfig script variables.
$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 CMM PC?" "ERROR"
    exit 0
}
. $getProfileScript

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

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

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

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