Set-StrictMode -Version Latest Import-Module (Join-Path $PSScriptRoot WindowsSettings.psm1) function Get-UserPathMap { param($Settings) $map = [ordered]@{} $stored = if ($null -ne $Settings -and $Settings.Contains('userPaths')) { $Settings.userPaths } else { @{} } foreach ($name in @('APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMDATA', 'SYSTEMROOT')) { $value = if ($stored.Contains($name)) { [string]$stored[$name] } else { [Environment]::GetEnvironmentVariable($name) } if (-not [string]::IsNullOrWhiteSpace($value)) { $map[$name] = $value } } return $map } function Resolve-ConfigTarget { param([Parameter(Mandatory)][string]$Target, [Parameter(Mandatory)]$PathMap) $unknown = [regex]::Matches($Target, '%([^%]+)%') | ForEach-Object { $_.Groups[1].Value } | Where-Object { $_ -notin $PathMap.Keys } if ($unknown) { throw "Unsupported path variable(s) in '$Target': $($unknown -join ', ')." } $resolved = $Target foreach ($name in $PathMap.Keys) { $resolved = $resolved.Replace("%$name%", [string]$PathMap[$name], [System.StringComparison]::OrdinalIgnoreCase) } $full = [System.IO.Path]::GetFullPath($resolved) if (-not [System.IO.Path]::IsPathFullyQualified($full)) { throw "Config target must be absolute: '$Target'." } return $full } function Resolve-ConfigSource { param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)][string]$Source) if ([System.IO.Path]::IsPathFullyQualified($Source)) { throw "Config source must be repository-relative: '$Source'." } $configRoot = [System.IO.Path]::GetFullPath((Join-Path $RepositoryRoot 'configs')) $candidate = [System.IO.Path]::GetFullPath((Join-Path $RepositoryRoot $Source)) $prefix = $configRoot.TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar) + [System.IO.Path]::DirectorySeparatorChar if (-not $candidate.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)) { throw "Config source escapes configs/: '$Source'." } if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { throw "Config source does not exist: '$Source'." } return $candidate } function Get-FileHashValue { param([Parameter(Mandatory)][string]$Path) (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() } function Get-ConfigPlan { param([Parameter(Mandatory)]$Configs, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$State, [Parameter(Mandatory)]$Settings) if (-not $State.Contains('configs')) { $State.configs = [ordered]@{} } $pathMap = Get-UserPathMap -Settings $Settings $destinations = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) $plan = [System.Collections.Generic.List[object]]::new() foreach ($config in @($Configs)) { $source = Resolve-ConfigSource -RepositoryRoot $RepositoryRoot -Source $config.source $target = if ($config.mode -in @('registry', 'windows-sounds', 'windows-power')) { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap } if (-not $destinations.Add($target)) { throw "Multiple configs resolve to '$target'." } $record = if ($State.configs.Contains($config.name)) { $State.configs[$config.name] } else { $null } if ($config.mode -eq 'copy') { $sourceHash = Get-FileHashValue -Path $source $targetExists = Test-Path -LiteralPath $target -PathType Leaf $targetHash = if ($targetExists) { Get-FileHashValue -Path $target } else { $null } if (-not $targetExists -and $null -eq $record) { $action = 'Create'; $reason = 'Destination is absent' } elseif ($null -eq $record) { $action = 'Conflict'; $reason = 'Existing destination is not managed' } elseif (-not $targetExists) { $action = 'Conflict'; $reason = 'Managed destination was deleted locally' } elseif ($targetHash -ne [string]$record.deployedHash) { $action = 'Conflict'; $reason = 'Managed destination was edited locally' } elseif ($targetHash -eq $sourceHash) { $action = 'None'; $reason = 'Content is current' } else { $action = 'Update'; $reason = 'Repository content changed' } $desired = $null $requiresAdmin = $false } else { $adapterPlan = Get-AdapterPlan -Config $config -Source $source -Target $target -Record $record $sourceHash = $adapterPlan.desiredHash $targetHash = $adapterPlan.currentHash $action = $adapterPlan.action $reason = $adapterPlan.reason $desired = $adapterPlan.desired $requiresAdmin = [bool]$adapterPlan.requiresAdmin } $plan.Add([pscustomobject]@{ kind = 'config'; name = $config.name; action = $action; reason = $reason source = $source; target = $target; sourceHash = $sourceHash; targetHash = $targetHash mode = $config.mode; desired = $desired; requiresAdmin = $requiresAdmin requiresPackage = if ($config.PSObject.Properties['requiresPackage']) { [string]$config.requiresPackage } else { $null } }) } return @($plan) } function Get-ConfigLocations { param( [Parameter(Mandatory)]$Configs, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$Settings, [string]$Name ) $pathMap = Get-UserPathMap -Settings $Settings $selected = @($Configs) if (-not [string]::IsNullOrWhiteSpace($Name)) { $selected = @($selected | Where-Object { $_.name -eq $Name }) if ($selected.Count -eq 0) { throw "Unknown config '$Name'." } } $locations = [System.Collections.Generic.List[object]]::new() foreach ($config in $selected) { $source = Resolve-ConfigSource -RepositoryRoot $RepositoryRoot -Source $config.source $target = if ($config.mode -in @('registry', 'windows-sounds', 'windows-power')) { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap } $targetExists = if ($config.mode -eq 'windows-power') { $IsWindows } else { [bool](Test-Path -LiteralPath $target -ErrorAction SilentlyContinue) } $locations.Add([pscustomobject]@{ kind = 'config'; name = [string]$config.name status = if ($targetExists) { 'Present' } else { 'Missing' } message = "Repository: $source | Computer: $target" mode = [string]$config.mode; source = $source; target = $target sourceExists = $true; targetExists = $targetExists }) } return @($locations) } function Export-ConfigCapture { param( [Parameter(Mandatory)]$Configs, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$Settings, [Parameter(Mandatory)][string]$Machine, [string]$Name, [string]$OutputPath ) if ([string]::IsNullOrWhiteSpace($OutputPath)) { $documents = [Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments) if ([string]::IsNullOrWhiteSpace($documents)) { $pathMap = Get-UserPathMap -Settings $Settings if (-not $pathMap.Contains('USERPROFILE')) { throw 'The Documents directory could not be resolved.' } $documents = Join-Path $pathMap.USERPROFILE 'Documents' } $captureName = "$Machine-$([DateTimeOffset]::Now.ToString('yyyyMMdd-HHmmss'))" $OutputPath = Join-Path (Join-Path $documents 'ConfigCentral\captures') $captureName } $captureRoot = [IO.Path]::GetFullPath($OutputPath) if (Test-Path -LiteralPath $captureRoot) { throw "Capture destination already exists: '$captureRoot'." } [void](New-Item -ItemType Directory -Path $captureRoot -Force) $selectedConfigs = @($Configs) if (-not [string]::IsNullOrWhiteSpace($Name)) { $selectedConfigs = @($selectedConfigs | Where-Object name -eq $Name) if ($selectedConfigs.Count -eq 0) { throw "Unknown config '$Name'." } } $locations = @(Get-ConfigLocations -Configs $selectedConfigs -RepositoryRoot $RepositoryRoot -Settings $Settings) $operations = [Collections.Generic.List[object]]::new() foreach ($config in $selectedConfigs) { $location = $locations | Where-Object name -eq $config.name | Select-Object -First 1 if (-not $location.targetExists) { $missingMessage = if ($config.name -eq 'mpc-hc-settings' -and $config.mode -eq 'registry') { 'MPC-HC has no registry settings to capture. Launch MPC-HC, save its settings in Windows registry mode, close both MPC-HC versions, then rerun cc capture.' } else { "Computer source is absent: $($location.target)" } $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Missing'; message = $missingMessage }) continue } if ($config.mode -in @('windows-sounds', 'windows-power')) { $captured = if ($config.mode -eq 'windows-sounds') { $sounds = Get-SoundDeclaration if (@($sounds.values | Where-Object { $_.path -and $_.value }).Count -eq 0) { [ordered]@{ schemaVersion = 1; disabled = $true } } else { $sounds } } else { $power = Get-PowerSettings [ordered]@{ schemaVersion = 1; batteryDisplayTimeoutSeconds = $power.batteryDisplayTimeoutSeconds } } $destination = Join-Path $captureRoot ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar) Write-JsonAtomic -Path $destination -Value $captured $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Captured'; message = $destination }) continue } if ($config.mode -eq 'copy') { $relative = ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar) $destination = Join-Path $captureRoot $relative $status = 'Captured' } elseif ($config.mode -eq 'registry' -and $config.name -eq 'mpc-hc-settings') { $destination = Join-Path $captureRoot 'review\mpc-hc-settings\settings.json' [void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force) & (Join-Path $RepositoryRoot 'tools\Export-MpcHcSettings.ps1') -OutputPath $destination -ThrowOnError 6>$null $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Review'; message = $destination }) continue } elseif ($config.name -eq 'nextcloud-settings') { $desired = Read-IniValues -Path $location.source $desiredCount = @($desired.Keys | ForEach-Object { $desired[$_].Count } | Measure-Object -Sum).Sum if (-not $desiredCount) { $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Excluded'; message = 'No allowlisted Nextcloud keys are declared; complete account config was not captured.' }) continue } $snapshot = Get-IniSnapshot -Path $location.target -Desired $desired $relative = ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar) $destination = Join-Path $captureRoot $relative [void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force) $lines = [Collections.Generic.List[string]]::new() $lines.Add('; Allowlisted Nextcloud preferences captured without account data.') foreach ($section in $desired.Keys) { $presentKeys = @($desired[$section].Keys | Where-Object { $null -ne $snapshot.values[$section][$_] }) if ($presentKeys.Count -eq 0) { continue } if ($section) { $lines.Add("[$section]") } foreach ($key in $presentKeys) { $lines.Add("$key=$($snapshot.values[$section][$key])") } } [IO.File]::WriteAllLines($destination, $lines, [Text.UTF8Encoding]::new($false)) $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Captured'; message = "$destination ($($snapshot.present) allowlisted values; account data excluded)" }) continue } else { $fileName = if ($config.mode -eq 'hosts-block') { 'hosts' } else { [IO.Path]::GetFileName($location.target) } $destination = Join-Path $captureRoot "review\$($config.name)\$fileName" $status = 'Review' } [void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force) Copy-Item -LiteralPath $location.target -Destination $destination $operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = $status; message = $destination }) } $readme = @( 'Config Central configuration capture', '', 'Files below configs/ retain their repository-relative paths.', 'Files below review/ are raw exports and must be curated before committing.', 'The complete Nextcloud configuration is never captured because it may contain credentials.' ) -join [Environment]::NewLine [IO.File]::WriteAllText((Join-Path $captureRoot 'README.txt'), $readme + [Environment]::NewLine, [Text.UTF8Encoding]::new($false)) $manifest = [ordered]@{ schemaVersion = 1 machine = $Machine capturedAt = [DateTimeOffset]::Now.ToString('o') repositoryRevision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot operations = @($operations) } [IO.File]::WriteAllText((Join-Path $captureRoot 'capture.json'), ($manifest | ConvertTo-Json -Depth 8), [Text.UTF8Encoding]::new($false)) return [pscustomobject]@{ path = $captureRoot; operations = @($operations) } } function Backup-ConfigTarget { param($Operation, $Paths) if (-not (Test-Path -LiteralPath $Operation.target -PathType Leaf)) { return $null } $folder = Join-Path $Paths.Backups $Operation.name [void](New-Item -ItemType Directory -Path $folder -Force) $backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).bak" Copy-Item -LiteralPath $Operation.target -Destination $backup -Force return $backup } function Invoke-ConfigOperation { param([Parameter(Mandatory)]$Operation, [Parameter(Mandatory)]$Paths, [Parameter(Mandatory)]$State, [switch]$Force) if ($Operation.action -eq 'None') { return [pscustomobject]@{ name = $Operation.name; status = 'Unchanged'; message = $Operation.reason } } if ($Operation.action -eq 'Conflict' -and -not $Force) { return [pscustomobject]@{ name = $Operation.name; status = 'Conflict'; message = "$($Operation.reason); use -ForceConfigs to back up and replace it" } } $backup = $null $temporary = $null $registryWarning = $null $registryTouched = $false $powerTouched = $false $powerBackup = $null $registryBackup = $null $previousRecord = if ($State.Contains('configs') -and $State.configs.Contains($Operation.name)) { $State.configs[$Operation.name] } else { $null } $deployedHash = $Operation.sourceHash try { if ($Operation.action -ne 'Adopt') { if ($Operation.mode -eq 'windows-power') { if ($Operation.target -ne 'active-power-scheme') { throw 'Invalid Windows power target.' } $folder = Join-Path $Paths.Backups $Operation.name $backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).json" $powerBackup = Get-PowerSettings Write-JsonAtomic -Path $backup -Value $powerBackup $powerTouched = $true Set-PowerSettings -Settings ([pscustomobject]@{ scheme = $powerBackup.scheme; batteryDisplayTimeoutSeconds = $Operation.desired.batteryDisplayTimeoutSeconds }) } elseif ($Operation.mode -in @('registry', 'windows-sounds')) { $folder = Join-Path $Paths.Backups $Operation.name [void](New-Item -ItemType Directory -Path $folder -Force) $backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).json" $registryBackup = Get-RegistryBackup -Root $Operation.target -Declaration $Operation.desired Write-JsonAtomic -Path $backup -Value $registryBackup $registryTouched = $true $writes = Set-RegistryDeclaration -Root $Operation.target -Declaration $Operation.desired if ($writes.failures.Count -gt 0) { # Keep detailed causes beside the backup; the terminal gets only key names. Write-JsonAtomic -Path "$backup.write-results.json" -Value $writes $failedKeys = @($writes.failures | ForEach-Object { $label = if ($_.name) { $_.name } else { '(Default)' } if ($_.path) { "$($_.path)\$label" } else { $label } }) $registryWarning = "Could not write registry key(s): $($failedKeys -join ', ')" if ($writes.written -eq 0 -or $Operation.mode -eq 'windows-sounds') { throw $registryWarning } Restore-RegistryDeclaration -Root $Operation.target -Backup $registryBackup -Only $writes.failures $deployedHash = (Get-RegistrySnapshot -Root $Operation.target -Declaration $Operation.desired).hash } } else { $backup = Backup-ConfigTarget -Operation $Operation -Paths $Paths $directory = Split-Path -Parent $Operation.target [void](New-Item -ItemType Directory -Path $directory -Force) $temporary = Join-Path $directory ".$([System.IO.Path]::GetFileName($Operation.target)).$([guid]::NewGuid().ToString('N')).tmp" if ($Operation.mode -eq 'copy') { Copy-Item -LiteralPath $Operation.source -Destination $temporary -Force } elseif ($Operation.mode -eq 'ini-overlay') { [IO.File]::WriteAllText($temporary, (Merge-IniFile -Target $Operation.target -Desired $Operation.desired), [Text.UTF8Encoding]::new($false)) } elseif ($Operation.mode -eq 'hosts-block') { [IO.File]::WriteAllText($temporary, (Set-HostsBlockContent -Target $Operation.target -Name $Operation.name -Lines $Operation.desired), [Text.UTF8Encoding]::new($false)) } else { throw "Unsupported config mode '$($Operation.mode)'." } [System.IO.File]::Move($temporary, $Operation.target, $true) } } if (-not $State.Contains('configs')) { $State.configs = [ordered]@{} } $State.configs[$Operation.name] = [ordered]@{ target = $Operation.target deployedHash = $deployedHash sourceHash = $Operation.sourceHash mode = $Operation.mode deployedAt = [DateTimeOffset]::UtcNow.ToString('o') lastBackup = $backup } Write-JsonAtomic -Path $Paths.State -Value $State if ($registryWarning) { return [pscustomobject]@{ name = $Operation.name; status = 'Warning'; message = $registryWarning } } return [pscustomobject]@{ name = $Operation.name; status = 'Succeeded'; message = if ($Operation.action -eq 'Adopt') { 'Adopted matching managed values' } elseif ($backup) { "Deployed; backup: $backup" } else { 'Deployed' } } } catch { $message = $_.Exception.Message if ($registryTouched -or $powerTouched) { if ($null -ne $previousRecord) { $State.configs[$Operation.name] = $previousRecord } elseif ($State.Contains('configs')) { $State.configs.Remove($Operation.name) } try { if ($registryTouched) { Restore-RegistryDeclaration -Root $Operation.target -Backup $registryBackup } else { Set-PowerSettings -Settings $powerBackup } Write-JsonAtomic -Path $Paths.State -Value $State $message += if ($registryTouched) { '; previous managed registry values restored' } else { '; previous power setting restored' } } catch { $message += "; rollback incomplete. Backup: $backup. $($_.Exception.Message)" } } return [pscustomobject]@{ name = $Operation.name; status = 'Failed'; message = $message } } finally { if ($temporary) { Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue } } } function Restore-ConfigBackup { param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)]$Paths, [Parameter(Mandatory)]$State) if (-not $State.Contains('configs') -or -not $State.configs.Contains($Name)) { throw "No managed state exists for config '$Name'." } $mode = if ($State.configs[$Name].Contains('mode')) { [string]$State.configs[$Name].mode } else { 'copy' } if ($mode -in @('registry', 'windows-sounds', 'windows-power')) { throw "Automatic restore is not supported for $mode config '$Name'; inspect its JSON backup and restore selected values deliberately." } if ($mode -eq 'hosts-block') { throw "Automatic restore is not supported for hosts config '$Name'; restore its backup from an administrator shell." } $folder = Join-Path $Paths.Backups $Name $backup = Get-ChildItem -LiteralPath $folder -Filter '*.bak' -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 if ($null -eq $backup) { throw "No backup exists for config '$Name'." } $target = [string]$State.configs[$Name].target $current = [pscustomobject]@{ name = $Name; target = $target } [void](Backup-ConfigTarget -Operation $current -Paths $Paths) [void](New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force) Copy-Item -LiteralPath $backup.FullName -Destination $target -Force $hash = Get-FileHashValue -Path $target $State.configs[$Name].deployedHash = $hash $State.configs[$Name].sourceHash = $hash $State.configs[$Name].deployedAt = [DateTimeOffset]::UtcNow.ToString('o') Write-JsonAtomic -Path $Paths.State -Value $State [pscustomobject]@{ name = $Name; status = 'Restored'; message = "Restored $($backup.FullName)" } } Export-ModuleMember -Function Get-UserPathMap, Resolve-ConfigTarget, Resolve-ConfigSource, Get-FileHashValue, Get-ConfigPlan, Get-ConfigLocations, Export-ConfigCapture, Invoke-ConfigOperation, Restore-ConfigBackup