# Map-SfldShare.ps1 - Map S: drive on user logon using SFLD creds from HKLM.
#
# Runs as the interactive user (BUILTIN\Users, Limited) so the drive
# mapping lands in the logged-in user's session. Reads username/password
# directly from HKLM:\SOFTWARE\GE\SFLD\Credentials\* and passes them
# inline to net use -- no Windows Credential Manager involvement.
#
# Why not the vendor's ConsumeCredentials.ps1: it calls
# New-StoredCredential -Persist LocalMachine which requires admin.
# ShopFloor is a non-admin user, so the cred-store step fails silently
# and the subsequent net use (which relies on those stored creds) has
# no authentication. Direct net use /user: bypasses the issue entirely.

$ErrorActionPreference = 'Continue'

$logDir = 'C:\Logs\SFLD'
if (-not (Test-Path $logDir)) {
    try { New-Item -Path $logDir -ItemType Directory -Force | Out-Null } catch { $logDir = $env:TEMP }
}
$logFile = Join-Path $logDir 'map-share.log'

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

Write-MapLog '=== Map-SfldShare start ==='

$credsBase = 'HKLM:\SOFTWARE\GE\SFLD\Credentials'
if (-not (Test-Path $credsBase)) {
    Write-MapLog 'No HKLM SFLD credentials yet - exiting'
    exit 0
}

foreach ($entry in (Get-ChildItem -Path $credsBase -ErrorAction SilentlyContinue)) {
    $p = Get-ItemProperty -Path $entry.PSPath -ErrorAction SilentlyContinue
    if (-not $p -or -not $p.TargetHost -or -not $p.Username -or -not $p.Password) { continue }

    $drive = $null
    $share = $null
    try { $drive = $p.DriveLetter } catch {}
    try { $share = $p.ShareName } catch {}

    if ([string]::IsNullOrWhiteSpace($drive) -or [string]::IsNullOrWhiteSpace($share)) { continue }

    $drive = $drive.TrimEnd(':') + ':'
    $share = $share.TrimStart('\')
    $uncPath = "\\$($p.TargetHost)\$share"

    # Skip if already mapped to the right target
    $existing = & net use $drive 2>&1
    if ($LASTEXITCODE -eq 0 -and ($existing -join "`n") -match [regex]::Escape($uncPath)) {
        Write-MapLog "$drive already mapped to $uncPath - skipping"
        continue
    }

    & net use $drive /delete /y 2>$null | Out-Null
    $out = & net use $drive $uncPath /user:$($p.Username) $($p.Password) /persistent:yes 2>&1
    if ($LASTEXITCODE -eq 0) {
        Write-MapLog "Mapped $drive -> $uncPath"
    } else {
        Write-MapLog "FAILED $drive -> $uncPath (exit $LASTEXITCODE): $out"
    }
}

Write-MapLog '=== Map-SfldShare end ==='
exit 0
