# Offline NTUSER.DAT prep for a ProfWiz-migrated Cascades user who is about
# to log in for the first time since the Folder Redirection GPO was fixed.
#
# Combines two fixes that otherwise would require separate post-logon cleanup:
#
#   1. UNPOISON — any User Shell Folders values pointing at
#      C:\Windows\system32\config\systemprofile\... (a ProfWiz side effect)
#      get reset to %USERPROFILE% defaults so the Folder Redirection CSE
#      doesn't hang trying to access SYSTEM's profile.
#
#   2. PRE-SEED UNC TARGETS — the legacy name (Personal) AND the modern
#      KnownFolder GUID forms for Documents and Downloads get set to the
#      UNC redirect path in advance, so the Explorer sidebar resolves
#      correctly on first login (no more "this file has no associated app"
#      post-login patch like we needed for Sharon Edwards).
#
# WHEN TO USE
#   Run BEFORE the user's first login after the Folder Redirection GPO has
#   been linked to their OU. Requires the user to be logged OFF so
#   NTUSER.DAT can be loaded as a hive.
#
# HOW TO RUN
#   ScreenConnect Backstage PowerShell (runs as SYSTEM) is the reliable path.
#   Example for Susan Hicks on DESKTOP-ROK7VNM:
#
#     .\prep-profile-for-redirection.ps1 `
#         -ProfilePath 'C:\Users\Susan.Hicks' `
#         -RedirectionRoot '\\CS-SERVER\homes' `
#         -SamName 'Susan.Hicks'
#
# SAFETY
#   - Idempotent: running twice is a no-op. Re-runs only log [KEEP].
#   - Never touches Desktop, Music, Pictures, Video, Favorites UNC paths
#     (only resets them to %USERPROFILE% defaults IF they're poisoned).
#   - Timestamped NTUSER.DAT backup at C:\ProfileBackups\ before any write.
#
# ROLLBACK
#   Copy-Item <backup> <ntuser-path> -Force   (while user logged off)

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [string]$ProfilePath,        # e.g. 'C:\Users\Susan.Hicks'

    [Parameter(Mandatory = $true)]
    [string]$RedirectionRoot,    # e.g. '\\CS-SERVER\homes'

    [Parameter(Mandatory = $true)]
    [string]$SamName,            # e.g. 'Susan.Hicks'

    [string]$BackupDir   = 'C:\ProfileBackups',
    [string]$TempHiveName = 'ProfileFix'
)

$ErrorActionPreference = 'Stop'

$ntuser = Join-Path $ProfilePath 'NTUSER.DAT'
if (-not (Test-Path $ntuser)) { throw "NTUSER.DAT not found at $ntuser" }

# Target UNC paths
$uncBase = "$RedirectionRoot\$SamName"
$docsUNC = "$uncBase\Documents"
$dlUNC   = "$uncBase\Downloads"

# Backup
New-Item -ItemType Directory -Path $BackupDir -Force | Out-Null
$stamp  = Get-Date -Format 'yyyyMMdd-HHmmss'
$leaf   = Split-Path $ProfilePath -Leaf
$backup = Join-Path $BackupDir "$leaf-NTUSER.DAT.$stamp.bak"
Copy-Item $ntuser $backup -Force
Write-Host "[OK] Backup -> $backup"

# Unload stale mount if any, then load hive
if (Test-Path "Registry::HKEY_USERS\$TempHiveName") {
    reg unload "HKU\$TempHiveName" 2>&1 | Out-Null
    Start-Sleep 1
}
$loadResult = reg load "HKU\$TempHiveName" $ntuser 2>&1
if ($LASTEXITCODE -ne 0) { throw "reg load failed: $loadResult" }
Write-Host "[OK] Hive loaded at HKU\$TempHiveName"

try {
    $USF = "Registry::HKEY_USERS\$TempHiveName\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
    $SF  = "Registry::HKEY_USERS\$TempHiveName\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"

    # --- Part 1: pre-seed UNC targets (legacy + GUID form, both hives) ---
    $targets = [ordered]@{
        'Personal'                                = $docsUNC   # legacy name for Documents
        '{FDD39AD0-238F-46AF-ADB4-6C85480369C7}'  = $docsUNC   # modern Documents KF GUID
        '{374DE290-123F-4565-9164-39C4925E467B}'  = $dlUNC     # modern Downloads KF GUID
    }

    Write-Host "`n--- Pre-seeding redirect targets ---"
    foreach ($name in $targets.Keys) {
        $new     = $targets[$name]
        $current = (Get-ItemProperty -Path $USF -Name $name -ErrorAction SilentlyContinue).$name

        if ($current -eq $new) {
            Write-Host "  [KEEP]    $name = '$current' (already correct)"
        } elseif ($null -eq $current) {
            New-ItemProperty -Path $USF -Name $name -Value $new -PropertyType ExpandString -Force | Out-Null
            Write-Host "  [ADDED]   $name = $new"
        } else {
            Set-ItemProperty -Path $USF -Name $name -Value $new -Type ExpandString
            Write-Host "  [CHANGED] $name : '$current' -> '$new'"
        }

        # Mirror into Shell Folders (REG_SZ, resolved path)
        New-ItemProperty -Path $SF -Name $name -Value $new -PropertyType String -Force -ErrorAction SilentlyContinue | Out-Null
    }

    # Legacy "My Documents" entry some older apps read
    New-ItemProperty -Path $SF -Name 'My Documents' -Value $docsUNC -PropertyType String -Force -ErrorAction SilentlyContinue | Out-Null

    # --- Part 2: unpoison anything still pointing at systemprofile ---
    $unpoison = [ordered]@{
        'My Music'    = '%USERPROFILE%\Music'
        'My Pictures' = '%USERPROFILE%\Pictures'
        'My Video'    = '%USERPROFILE%\Videos'
        'Favorites'   = '%USERPROFILE%\Favorites'
    }
    $poisonPrefix = 'C:\Windows\system32\config\systemprofile'

    Write-Host "`n--- Unpoisoning non-redirected shell folders ---"
    foreach ($name in $unpoison.Keys) {
        $new     = $unpoison[$name]
        $current = (Get-ItemProperty -Path $USF -Name $name -ErrorAction SilentlyContinue).$name

        if ($null -eq $current) {
            New-ItemProperty -Path $USF -Name $name -Value $new -PropertyType ExpandString -Force | Out-Null
            Write-Host "  [ADDED]   $name = $new"
        } elseif ($current -like "$poisonPrefix*") {
            Set-ItemProperty -Path $USF -Name $name -Value $new -Type ExpandString
            Write-Host "  [CHANGED] $name : '$current' -> '$new' (was poisoned)"
        } else {
            Write-Host "  [KEEP]    $name = '$current' (not poisoned)"
        }
    }
} finally {
    # Release any handles so the hive can unload cleanly
    [gc]::Collect()
    Start-Sleep 2
    reg unload "HKU\$TempHiveName" 2>&1 | Out-Null
    Write-Host "[OK] Hive unloaded"
}

Write-Host "`nBackup: $backup"
Write-Host "Rollback: Copy-Item '$backup' '$ntuser' -Force  (while user logged off)"
Write-Host ""
Write-Host "Next step: have the user sign in. The Folder Redirection CSE will apply the"
Write-Host "GPO (no hang because hive is clean) and the sidebar will resolve correctly"
Write-Host "because the GUID-form shell folders already point at the UNC target."
