Private/ProfileInternals.ps1

function Assert-PGWindows {
    $isWindowsPlatform = [System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT
    if (-not $isWindowsPlatform) {
        throw 'ProfileGuardian commands require Windows.'
    }
}

function Assert-PGAdministrator {
    Assert-PGWindows

    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = [Security.Principal.WindowsPrincipal]::new($identity)
    $administrator = [Security.Principal.WindowsBuiltInRole]::Administrator

    if (-not $principal.IsInRole($administrator)) {
        throw 'Profile removal requires an elevated PowerShell session.'
    }
}

function Resolve-PGDrive {
    param(
        [string]$Drive
    )

    if ([string]::IsNullOrWhiteSpace($Drive)) {
        $Drive = $env:SystemDrive
    }
    if ([string]::IsNullOrWhiteSpace($Drive)) {
        $Drive = 'C:'
    }
    if ($Drive -notmatch '^[A-Za-z]:$') {
        throw "Drive must use the form 'C:'. Received '$Drive'."
    }

    return $Drive.ToUpperInvariant()
}

function Resolve-PGProfileRoot {
    param(
        [string]$Drive,

        [string]$ProfileRoot
    )

    if ([string]::IsNullOrWhiteSpace($ProfileRoot)) {
        try {
            $profileList = Get-ItemProperty `
                -LiteralPath 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' `
                -Name ProfilesDirectory `
                -ErrorAction Stop
            $ProfileRoot = [string]$profileList.ProfilesDirectory
        }
        catch {
            $ProfileRoot = $null
        }
    }

    if ([string]::IsNullOrWhiteSpace($ProfileRoot)) {
        $ProfileRoot = "$(Resolve-PGDrive -Drive $Drive)\Users"
    }

    $expandedRoot = [Environment]::ExpandEnvironmentVariables($ProfileRoot)
    if ($expandedRoot -notmatch '^[A-Za-z]:[\\/]') {
        throw "ProfileRoot must be an absolute local path. Received '$ProfileRoot'."
    }

    return ConvertTo-PGCanonicalWindowsPath -Path $expandedRoot
}

function ConvertTo-PGCanonicalWindowsPath {
    param(
        [Parameter(Mandatory)]
        [string]$Path
    )

    $normalised = $Path.Replace('/', '\').TrimEnd('\')
    if ($normalised -notmatch '^[A-Za-z]:\\') {
        throw "Path must use an absolute local drive path. Received '$Path'."
    }

    $segments = @($normalised.Substring(3).Split('\') | Where-Object { $_ -ne '' })
    if ($segments -contains '.' -or $segments -contains '..') {
        throw "Path cannot contain relative segments. Received '$Path'."
    }

    $drive = $normalised.Substring(0, 2).ToUpperInvariant()
    if ($segments.Count -eq 0) {
        return "$drive\"
    }

    return "$drive\$($segments -join '\')"
}

function Get-PGDriveFromProfileRoot {
    param(
        [Parameter(Mandatory)]
        [string]$ProfileRoot
    )

    if ($ProfileRoot -notmatch '^(?<Drive>[A-Za-z]:)\\') {
        throw "Cannot determine a local drive from ProfileRoot '$ProfileRoot'."
    }

    return $Matches.Drive.ToUpperInvariant()
}

function ConvertTo-PGUInt32 {
    param(
        [Parameter(Mandatory)]
        $Value
    )

    $numericValue = [int64]$Value
    if ($numericValue -lt 0) {
        return [BitConverter]::ToUInt32([BitConverter]::GetBytes([int32]$numericValue), 0)
    }

    return [uint32]$numericValue
}

function ConvertFrom-PGFileTimePair {
    param(
        $Low,
        $High
    )

    if ($null -eq $Low -or $null -eq $High) {
        return $null
    }

    try {
        $lowUnsigned = ConvertTo-PGUInt32 -Value $Low
        $highUnsigned = ConvertTo-PGUInt32 -Value $High
        $fileTime = ([uint64]$highUnsigned -shl 32) -bor [uint64]$lowUnsigned
        if ($fileTime -eq 0 -or $fileTime -gt [int64]::MaxValue) {
            return $null
        }

        return [DateTime]::FromFileTimeUtc([int64]$fileTime).ToLocalTime()
    }
    catch {
        return $null
    }
}

function Get-PGProfileActivity {
    param(
        [Parameter(Mandatory)]
        [string]$Sid,

        [Parameter(Mandatory)]
        [string]$LocalPath,

        $LastUseTime
    )

    $profileListPath = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$Sid"
    $registryValues = $null

    try {
        $registryValues = Get-ItemProperty -LiteralPath $profileListPath -ErrorAction Stop
    }
    catch {
        $registryValues = $null
    }

    $activity = @()
    if ($null -ne $LastUseTime) {
        try {
            $lastUse = [datetime]$LastUseTime
            if ($lastUse -gt [datetime]::MinValue) {
                $activity += [pscustomobject]@{
                    Timestamp = $lastUse
                    Source    = 'Win32UserProfileLastUseTime'
                }
            }
        }
        catch {
            Write-Verbose 'Ignoring an invalid Win32_UserProfile LastUseTime value.'
        }
    }
    if ($null -ne $registryValues) {
        $pairs = @(
            @{ Name = 'ProfileLoad'; Low = 'LocalProfileLoadTimeLow'; High = 'LocalProfileLoadTimeHigh' }
            @{ Name = 'ProfileUnload'; Low = 'LocalProfileUnloadTimeLow'; High = 'LocalProfileUnloadTimeHigh' }
            @{ Name = 'CleanupCheck'; Low = 'LocalProfileCleanupCheckTimeLow'; High = 'LocalProfileCleanupCheckTimeHigh' }
        )

        foreach ($pair in $pairs) {
            $value = ConvertFrom-PGFileTimePair -Low $registryValues.($pair.Low) -High $registryValues.($pair.High)
            if ($null -ne $value) {
                $activity += [pscustomobject]@{
                    Timestamp = $value
                    Source    = $pair.Name
                }
            }
        }
    }

    if ($activity.Count -gt 0) {
        $latest = $activity | Sort-Object -Property Timestamp -Descending | Select-Object -First 1
    }
    else {
        $latest = $null
        foreach ($fileName in @('NTUSER.MAN', 'NTUSER.DAT')) {
            $path = Join-Path -Path $LocalPath -ChildPath $fileName
            if (Test-Path -LiteralPath $path -PathType Leaf) {
                $item = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
                if ($null -ne $item) {
                    $latest = [pscustomobject]@{
                        Timestamp = $item.LastWriteTime
                        Source    = $fileName
                    }
                    break
                }
            }
        }
    }

    if ($null -eq $latest -or $latest.Timestamp -gt (Get-Date).AddMinutes(5)) {
        return $null
    }

    return $latest
}

function Test-PGProfileBaseEligibility {
    param(
        [Parameter(Mandatory)]
        $UserProfile,

        [Parameter(Mandatory)]
        [string]$ProfileRoot,

        [string[]]$ProtectedProfileName
    )

    $sid = [string]$UserProfile.SID
    $localPath = [string]$UserProfile.LocalPath

    if ([string]::IsNullOrWhiteSpace($sid)) {
        return 'MissingSid'
    }
    if ([string]::IsNullOrWhiteSpace($localPath)) {
        return 'MissingPath'
    }
    if ([bool]$UserProfile.Special) {
        return 'SpecialProfile'
    }
    if ([bool]$UserProfile.Loaded) {
        return 'LoadedProfile'
    }
    if ($sid -match '-500$') {
        return 'BuiltInAdministrator'
    }
    if ($sid -in @('S-1-5-18', 'S-1-5-19', 'S-1-5-20')) {
        return 'WellKnownServiceProfile'
    }

    try {
        $fullRoot = ConvertTo-PGCanonicalWindowsPath -Path $ProfileRoot
        $fullPath = ConvertTo-PGCanonicalWindowsPath -Path $localPath
        $lastSeparator = $fullPath.LastIndexOf('\')
        $parent = if ($lastSeparator -gt 2) { $fullPath.Substring(0, $lastSeparator) } else { $null }
    }
    catch {
        return 'InvalidProfilePath'
    }

    if ($null -eq $parent -or -not $parent.Equals($fullRoot, [StringComparison]::OrdinalIgnoreCase)) {
        return 'OutsideProfileRoot'
    }

    if (-not (Test-Path -LiteralPath $fullPath -PathType Container)) {
        return 'MissingOrInaccessibleProfileDirectory'
    }

    try {
        $profileDirectory = Get-Item -LiteralPath $fullPath -Force -ErrorAction Stop
    }
    catch {
        return 'ProfileDirectoryInspectionFailed'
    }
    if ($profileDirectory.Attributes -band [IO.FileAttributes]::ReparsePoint) {
        return 'ReparsePointProfile'
    }

    $profileName = Split-Path -Path $fullPath -Leaf
    $defaultProtectedNames = @(
        'Administrator'
        'Default'
        'Default User'
        'Public'
        'All Users'
        'defaultuser0'
        'WDAGUtilityAccount'
        'systemprofile'
        'LocalService'
        'NetworkService'
    )

    $allProtectedNames = @($defaultProtectedNames) + @($ProtectedProfileName)
    if ($profileName -in $allProtectedNames) {
        return 'ProtectedProfile'
    }

    return $null
}

function Get-PGProfileBySid {
    param(
        [Parameter(Mandatory)]
        [ValidatePattern('^S-\d(?:-\d+)+$')]
        [string]$Sid
    )

    $escapedSid = $Sid.Replace("'", "''")
    return Get-CimInstance -ClassName Win32_UserProfile -Filter "SID='$escapedSid'" -ErrorAction Stop |
        Select-Object -First 1
}

function Invoke-PGProfileCimRemoval {
    param(
        [Parameter(Mandatory)]
        $UserProfile
    )

    Remove-CimInstance -InputObject $UserProfile -ErrorAction Stop
}

function Resolve-PGLogDirectory {
    param(
        [string]$LogDirectory
    )

    if (-not [string]::IsNullOrWhiteSpace($LogDirectory)) {
        return $LogDirectory
    }
    if (-not [string]::IsNullOrWhiteSpace($env:ProgramData)) {
        return Join-Path $env:ProgramData 'ProfileGuardian\Logs'
    }

    return Join-Path ([System.IO.Path]::GetTempPath()) 'ProfileGuardian\Logs'
}

function Enter-PGRunLock {
    param(
        [Parameter(Mandatory)]
        [ValidatePattern('^[A-Za-z]:$')]
        [string]$Drive
    )

    $isWindowsPlatform = [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
    $commonData = if ($isWindowsPlatform) {
        [Environment]::GetFolderPath([Environment+SpecialFolder]::CommonApplicationData)
    }
    else {
        [IO.Path]::GetTempPath()
    }
    if ([string]::IsNullOrWhiteSpace($commonData)) {
        $commonData = [IO.Path]::GetTempPath()
    }

    $lockDirectory = Join-Path $commonData 'ProfileGuardian\Locks'
    New-Item -ItemType Directory -Path $lockDirectory -Force -ErrorAction Stop | Out-Null
    $lockPath = Join-Path $lockDirectory "$($Drive.Substring(0, 1).ToUpperInvariant()).lock"

    try {
        return [IO.File]::Open($lockPath, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None)
    }
    catch [IO.IOException] {
        throw "Another ProfileGuardian run is active for drive '$Drive'."
    }
}

function Exit-PGRunLock {
    param(
        $LockHandle
    )

    if ($null -ne $LockHandle) {
        $LockHandle.Dispose()
    }
}

function Invoke-PGLogRotation {
    param(
        [Parameter(Mandatory)]
        [string]$Path,

        [long]$MaximumBytes = 5MB
    )

    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
        return
    }

    $file = Get-Item -LiteralPath $Path -ErrorAction Stop
    if ($file.Length -lt $MaximumBytes) {
        return
    }

    $archivePath = "$Path.1"
    Move-Item -LiteralPath $Path -Destination $archivePath -Force -ErrorAction Stop
}

function Wait-PGProfileAbsent {
    param(
        [Parameter(Mandatory)]
        [string]$Sid,

        [ValidateRange(1, 30)]
        [int]$TimeoutSeconds = 5
    )

    $stopwatch = [Diagnostics.Stopwatch]::StartNew()
    do {
        if ($null -eq (Get-PGProfileBySid -Sid $Sid)) {
            return $true
        }

        Start-Sleep -Milliseconds 200
    } while ($stopwatch.Elapsed.TotalSeconds -lt $TimeoutSeconds)

    return $false
}

function Write-PGRunRecord {
    param(
        [Parameter(Mandatory)]
        [string]$LogDirectory,

        [Parameter(Mandatory)]
        [ValidateSet('INFO', 'WARN', 'ERROR')]
        [string]$Level,

        [Parameter(Mandatory)]
        [string]$Message,

        [hashtable]$Data = @{}
    )

    New-Item -ItemType Directory -Path $LogDirectory -Force -ErrorAction Stop | Out-Null

    $timestamp = (Get-Date).ToUniversalTime().ToString('o')
    $record = [ordered]@{
        timestamp = $timestamp
        level     = $Level
        message   = $Message
        data      = $Data
    }

    $textPath = Join-Path $LogDirectory 'ProfileGuardian.log'
    $jsonPath = Join-Path $LogDirectory 'ProfileGuardian.jsonl'

    Invoke-PGLogRotation -Path $textPath
    Invoke-PGLogRotation -Path $jsonPath

    $dataJson = $Data | ConvertTo-Json -Depth 5 -Compress
    Add-Content -LiteralPath $textPath -Value "$timestamp [$Level] $Message $dataJson" -Encoding UTF8 -ErrorAction Stop
    Add-Content -LiteralPath $jsonPath -Value ($record | ConvertTo-Json -Depth 5 -Compress) -Encoding UTF8 -ErrorAction Stop
}