# Register-MapSfldShare.ps1 - Stage Map-SfldShare.ps1 + register an
# HKLM\Run entry that maps S: for any interactive user (SupportUser,
# ShopFloor, any future end-user accounts).
#
# Why HKLM\Run instead of a scheduled task: Run fires at Explorer
# startup in the logged-in user's interactive session with their full
# token + HKCU mounted. No principal/LogonType/group-SID plumbing, no
# "task fires in session 0 but drive not visible to Explorer" class of
# bugs. Works for every BUILTIN\Users member with no extra logic.
#
# Why not the vendor's ConsumeCredentials.ps1: it calls
# New-StoredCredential -Persist LocalMachine (needs admin) before net
# use. ShopFloor is non-admin, so the cred-store fails and net use has
# no auth. Our Map-SfldShare.ps1 reads HKLM creds directly and passes
# them inline to net use /user: -- no Credential Manager needed.

$ErrorActionPreference = 'Continue'

$installRoot = 'C:\Program Files\GE\SfldShare'
$mapScript   = Join-Path $installRoot 'Map-SfldShare.ps1'
$logDir      = 'C:\Logs\SFLD'
$logFile     = Join-Path $logDir 'register-mapshare.log'
$runKey      = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
$runValue    = 'GE Map SFLD Share'
$legacyTask  = 'GE Shopfloor Map S: Drive'

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

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

Write-RegLog '=== Register-MapSfldShare start ==='

# Stage our Map-SfldShare.ps1 to a persistent location
if (-not (Test-Path $installRoot)) {
    New-Item -Path $installRoot -ItemType Directory -Force | Out-Null
}
$src = Join-Path $PSScriptRoot 'lib\Map-SfldShare.ps1'
if (Test-Path $src) {
    Copy-Item -Path $src -Destination $mapScript -Force
    Write-RegLog "Staged $src -> $mapScript"
} else {
    Write-RegLog "Map-SfldShare.ps1 not found at $src - cannot register"
    exit 1
}

# Remove the legacy scheduled task if it exists (left behind by older
# imaging runs that used the scheduled-task approach).
if (Get-ScheduledTask -TaskName $legacyTask -ErrorAction SilentlyContinue) {
    try {
        Unregister-ScheduledTask -TaskName $legacyTask -Confirm:$false -ErrorAction Stop
        Write-RegLog "Removed legacy scheduled task '$legacyTask'"
    } catch {
        Write-RegLog "Failed to remove legacy task '$legacyTask': $_"
    }
}

# Register HKLM\Run entry. Runs at Explorer startup for every
# interactive user in that user's session.
try {
    $command = '"{0}" -NoProfile -ExecutionPolicy Bypass -File "{1}"' -f `
        "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe", $mapScript

    if (-not (Test-Path $runKey)) {
        New-Item -Path $runKey -Force | Out-Null
    }
    New-ItemProperty -Path $runKey -Name $runValue -Value $command -PropertyType String -Force | Out-Null
    Write-RegLog "Set $runKey\$runValue = $command"
} catch {
    Write-RegLog "FAILED to register Run key: $_"
    exit 1
}

Write-RegLog '=== Register-MapSfldShare end ==='
exit 0
