config-central/install.ps1

140 lines
5.7 KiB
PowerShell

#requires -Version 5.1
[CmdletBinding()]
param(
[string]$Machine = $env:CONFIG_CENTRAL_MACHINE,
[string]$Branch = $env:CONFIG_CENTRAL_BRANCH,
[switch]$SkipApply
)
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 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-Warning "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-Warning "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' }
& $windowsPowerShell @arguments
$bootstrapExitCode = $LASTEXITCODE
if ($bootstrapExitCode -ne 0) { throw "Bootstrap failed with exit code $bootstrapExitCode." }
Write-Host ''
Write-Host "Config Central is ready for '$Machine'."
Write-Host 'Use cc sync for normal updates, or rerun this installer to repair the setup.'
}
finally {
Remove-Item -LiteralPath $bootstrapPath -Force -ErrorAction SilentlyContinue
}