config-central/install.ps1

212 lines
9.1 KiB
PowerShell

#requires -Version 5.1
[CmdletBinding()]
param(
[string]$Machine = $env:CONFIG_CENTRAL_MACHINE,
[string]$Branch = $env:CONFIG_CENTRAL_BRANCH,
[switch]$SkipApply,
[switch]$PreserveLocalConfigs
)
# Kept identical in standalone entrypoints; verified by Output.Tests.ps1.
function Write-ConfigCentralMessage {
param([string]$Message, [ValidateSet('Info', 'Success', 'Warning', 'Error')][string]$Level = 'Info')
$color = switch ($Level) {
'Success' { 'Green' }
'Warning' { 'Yellow' }
'Error' { 'Red' }
default { 'Cyan' }
}
$redirected = if ($Level -eq 'Error') { [Console]::IsErrorRedirected } else { [Console]::IsOutputRedirected }
$useColor = -not $redirected -and $null -eq [Environment]::GetEnvironmentVariable('NO_COLOR')
if ($Level -eq 'Error') {
$previous = $null
try {
if ($useColor) { $previous = [Console]::ForegroundColor; [Console]::ForegroundColor = $color }
[Console]::Error.WriteLine($Message)
}
finally { if ($null -ne $previous) { [Console]::ForegroundColor = $previous } }
}
elseif ($useColor) { Write-Host $Message -ForegroundColor $color }
else { Write-Host $Message }
}
try {
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$repository = 'https://proxy.dandaedre.com/gitea/Beffroi/config-central.git'
$repositoryApi = 'https://proxy.dandaedre.com/gitea/api/v1/repos/Beffroi/config-central'
$rawRoot = 'https://proxy.dandaedre.com/gitea/Beffroi/config-central/raw/branch'
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
throw 'Config Central installer runs only on Windows.'
}
if ([string]::IsNullOrWhiteSpace($env:TEMP) -or [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
throw 'The interactive Windows user profile is unavailable.'
}
if ([string]::IsNullOrWhiteSpace($Branch)) {
$Branch = 'main'
}
elseif ($Branch -notmatch '^[A-Za-z0-9._/-]+$') {
throw "Invalid branch name '$Branch'."
}
if (-not [string]::IsNullOrWhiteSpace($Machine) -and $Machine -notmatch '^[a-z0-9][a-z0-9-]*$') {
throw "Invalid machine name '$Machine'."
}
if ($env:CONFIG_CENTRAL_SKIP_APPLY -eq '1') { $SkipApply = $true }
function Write-SetupFailure {
param([int]$ExitCode)
Write-Host ''
switch ($ExitCode) {
5 {
Write-ConfigCentralMessage -Level Warning -Message 'Setup finished with some items needing attention.'
Write-Host 'Successful changes were kept. Review the Failed, Conflict, or Skipped items above.'
Write-Host 'Fix the reported issue, then rerun setup; completed items will be checked and skipped when current.'
}
6 {
Write-ConfigCentralMessage -Level Warning -Message 'Setup completed. Windows needs a restart to finish installation.'
Write-Host 'Restart when convenient; Config Central will not restart this computer automatically.'
}
10 {
Write-ConfigCentralMessage -Level Warning -Message 'Another Config Central update is already running.'
Write-Host 'Wait for it to finish, then rerun setup.'
}
default {
Write-ConfigCentralMessage -Level Error -Message "Setup could not complete (exit code $ExitCode)."
Write-Host 'Review the diagnostic above, correct the problem, and rerun setup.'
}
}
if ($ExitCode -ne 6) {
Write-Host 'Run cc doctor in a new terminal to check setup.'
Write-Host ('Deployment logs: ' + (Join-Path $env:LOCALAPPDATA 'ConfigCentral\logs'))
}
}
function Get-SavedMachine {
$settingsPath = Join-Path $env:LOCALAPPDATA 'ConfigCentral\settings.json'
if (-not (Test-Path -LiteralPath $settingsPath -PathType Leaf)) { return $null }
try {
$settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
if ($settings.machine -match '^[a-z0-9][a-z0-9-]*$') { return [string]$settings.machine }
}
catch { Write-ConfigCentralMessage -Level Warning -Message "Ignoring unreadable existing settings: $($_.Exception.Message)" }
return $null
}
function Get-AvailableMachines {
$encodedBranch = [Uri]::EscapeDataString($Branch)
try {
$entries = Invoke-RestMethod -Uri "$repositoryApi/contents/machines?ref=$encodedBranch" -UseBasicParsing
return @(
$entries |
Where-Object { $_.type -eq 'file' -and $_.name -match '^[a-z0-9][a-z0-9-]*\.json$' } |
ForEach-Object { $_.name.Substring(0, $_.name.Length - 5) } |
Sort-Object -Unique
)
}
catch {
Write-ConfigCentralMessage -Level Warning -Message "Could not list machine manifests: $($_.Exception.Message)"
return @()
}
}
function Select-ConfigCentralMachine {
param([string]$Requested, [string]$Saved, [string[]]$Available)
if (-not [string]::IsNullOrWhiteSpace($Requested)) {
if ($Available.Count -gt 0 -and $Requested -notin $Available) {
throw "Machine manifest '$Requested' does not exist on branch '$Branch'."
}
return $Requested
}
if (-not [string]::IsNullOrWhiteSpace($Saved) -and ($Available.Count -eq 0 -or $Saved -in $Available)) {
Write-Host "Reusing configured machine '$Saved'."
return $Saved
}
$computerName = if ($env:COMPUTERNAME) { $env:COMPUTERNAME.ToLowerInvariant() } else { $null }
if ($computerName -and $computerName -in $Available) {
Write-Host "Using machine manifest '$computerName' matching this computer name."
return $computerName
}
if ($Available.Count -eq 1) {
Write-Host "Using the only available machine manifest, '$($Available[0])'."
return $Available[0]
}
if ($Available.Count -eq 0) {
$answer = Read-Host 'Machine manifest name'
if ($answer -notmatch '^[a-z0-9][a-z0-9-]*$') { throw "Invalid machine name '$answer'." }
return $answer
}
Write-Host 'Available machine manifests:'
for ($index = 0; $index -lt $Available.Count; $index++) {
Write-Host (" {0}. {1}" -f ($index + 1), $Available[$index])
}
$selection = Read-Host 'Select a machine number or name'
$number = 0
if ([int]::TryParse($selection, [ref]$number) -and $number -ge 1 -and $number -le $Available.Count) {
return $Available[$number - 1]
}
if ($selection -in $Available) { return $selection }
throw "Unknown machine selection '$selection'."
}
$availableMachines = @(Get-AvailableMachines)
$Machine = Select-ConfigCentralMachine -Requested $Machine -Saved (Get-SavedMachine) -Available $availableMachines
$bootstrapPath = Join-Path $env:TEMP "config-central-bootstrap-$([guid]::NewGuid().ToString('N')).ps1"
$encodedBranch = [Uri]::EscapeDataString($Branch)
$bootstrapUrl = "$rawRoot/$encodedBranch/bootstrap.ps1"
try {
Write-Host "Downloading Config Central bootstrap for branch '$Branch'..."
Invoke-RestMethod -Uri $bootstrapUrl -OutFile $bootstrapPath -UseBasicParsing
if (-not (Test-Path -LiteralPath $bootstrapPath -PathType Leaf) -or (Get-Item -LiteralPath $bootstrapPath).Length -eq 0) {
throw 'Downloaded bootstrap is missing or empty.'
}
$tokens = $null
$parseErrors = $null
[void][System.Management.Automation.Language.Parser]::ParseFile($bootstrapPath, [ref]$tokens, [ref]$parseErrors)
if ($parseErrors.Count -gt 0) { throw "Downloaded bootstrap does not parse: $($parseErrors[0].Message)" }
$windowsPowerShell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
$arguments = @(
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $bootstrapPath,
'-Repository', $repository, '-Branch', $Branch, '-Machine', $Machine
)
if ($SkipApply) { $arguments += '-SkipApply' }
if ($PreserveLocalConfigs) { $arguments += '-PreserveLocalConfigs' }
& $windowsPowerShell @arguments
$bootstrapExitCode = $LASTEXITCODE
if ($bootstrapExitCode -ne 0) {
Write-SetupFailure -ExitCode $bootstrapExitCode
# File execution returns a process exit code. Web execution keeps the
# interactive terminal open and exposes the status through LASTEXITCODE.
if ($MyInvocation.MyCommand.PSObject.Properties['Path']) { exit $bootstrapExitCode }
$global:LASTEXITCODE = $bootstrapExitCode
return
}
Write-Host ''
Write-ConfigCentralMessage -Level Success -Message "Config Central is ready for '$Machine'."
Write-Host 'Run the web update-configs.ps1 command for config updates, or rerun this installer to repair setup.'
}
finally {
Remove-Item -LiteralPath $bootstrapPath -Force -ErrorAction SilentlyContinue
}
$global:LASTEXITCODE = 0
}
catch {
Write-ConfigCentralMessage -Level Error -Message "Setup could not complete: $($_.Exception.Message)"
Write-Host 'Correct the reported issue and rerun the command. Completed changes are kept.'
$code = if ($_.Exception.Data.Contains('ExitCode')) { [int]$_.Exception.Data['ExitCode'] } else { 2 }
if ($MyInvocation.MyCommand.PSObject.Properties['Path']) { exit $code }
$global:LASTEXITCODE = $code
return
}