diff --git a/TASKS.md b/TASKS.md index 0b0ef5d..2d1eaf4 100644 --- a/TASKS.md +++ b/TASKS.md @@ -70,9 +70,9 @@ Complete the core CLI and manual workflow before optional automation or a TUI. and keeping user operations in the user session. - [x] Secure machine-level state and elevated-worker inputs against unintended modification; handle concurrent user sessions. -- [ ] Implement PowerShell 5.1 bootstrap to check or establish WinGet, Git, and +- [x] Implement PowerShell 5.1 bootstrap to check or establish WinGet, Git, and PowerShell 7, with explicit handling of missing WinGet registration. -- [ ] Clone the repository, save machine selection, install the launcher, and +- [x] Clone the repository, save machine selection, install the launcher, and perform the first apply. - [ ] Verify bootstrap can resume after interrupted prerequisite installation. diff --git a/bootstrap.ps1 b/bootstrap.ps1 new file mode 100644 index 0000000..e6a8c00 --- /dev/null +++ b/bootstrap.ps1 @@ -0,0 +1,124 @@ +#requires -Version 5.1 +[CmdletBinding()] +param( + [string]$Repository, + [ValidatePattern('^[a-z0-9][a-z0-9-]*$')][string]$Machine, + [ValidatePattern('^[A-Za-z0-9._/-]+$')][string]$Branch = 'main', + [string]$Checkout = (Join-Path $env:LOCALAPPDATA 'ConfigCentral\repository'), + [switch]$SkipApply, + [switch]$RepairWinGetOnly +) + +Set-StrictMode -Version 2.0 +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + +function Test-Administrator { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($identity) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +function Invoke-BootstrapWingetInstall { + param([Parameter(Mandatory = $true)][string]$Id) + & winget.exe install --id $Id --exact --source winget --silent --disable-interactivity --accept-package-agreements --accept-source-agreements --scope machine + if ($LASTEXITCODE -ne 0) { throw "WinGet failed to install '$Id' (exit $LASTEXITCODE)." } +} + +function Ensure-WinGet { + if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return } + try { + Add-AppxPackage -RegisterByFamilyName -MainPackage Microsoft.DesktopAppInstaller_8wekyb3d8bbwe -ErrorAction Stop + } + catch { Write-Verbose "Desktop App Installer registration did not restore WinGet: $($_.Exception.Message)" } + if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return } + + if (-not (Test-Administrator)) { + $arguments = "-NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -RepairWinGetOnly" + $repair = Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $arguments -Wait -PassThru + if ($repair.ExitCode -ne 0) { throw "Elevated WinGet repair failed (exit $($repair.ExitCode))." } + if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { + $windowsApps = Join-Path $env:LOCALAPPDATA 'Microsoft\WindowsApps' + if (($env:Path -split ';') -notcontains $windowsApps) { $env:Path = "$env:Path;$windowsApps" } + } + if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { throw 'WinGet was repaired but is unavailable in the current user session.' } + return + } + if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) { Install-PackageProvider -Name NuGet -Force -Scope AllUsers | Out-Null } + Install-Module -Name Microsoft.WinGet.Client -Repository PSGallery -Force -Scope AllUsers -AllowClobber + Repair-WinGetPackageManager -AllUsers + if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { throw 'WinGet repair completed but winget.exe remains unavailable.' } +} + +if ($RepairWinGetOnly) { + if (-not (Test-Administrator)) { throw 'WinGet repair requires administrator rights.' } + if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) { Install-PackageProvider -Name NuGet -Force -Scope AllUsers | Out-Null } + Install-Module -Name Microsoft.WinGet.Client -Repository PSGallery -Force -Scope AllUsers -AllowClobber + Repair-WinGetPackageManager -AllUsers + exit 0 +} + +if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Config Central bootstrap runs only on Windows.' } +if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA) -or [string]::IsNullOrWhiteSpace($env:USERPROFILE)) { throw 'The interactive user profile is unavailable.' } +if ([string]::IsNullOrWhiteSpace($Repository) -or [string]::IsNullOrWhiteSpace($Machine)) { throw 'Bootstrap requires -Repository and -Machine.' } + +Write-Host 'Checking WinGet...' +Ensure-WinGet +if (-not (Get-Command git.exe -ErrorAction SilentlyContinue)) { Invoke-BootstrapWingetInstall -Id 'Git.Git' } +if (-not (Get-Command pwsh.exe -ErrorAction SilentlyContinue)) { Invoke-BootstrapWingetInstall -Id 'Microsoft.PowerShell' } + +$git = (Get-Command git.exe -ErrorAction Stop).Source +if (Test-Path -LiteralPath (Join-Path $Checkout '.git')) { + Push-Location $Checkout + try { + $dirty = & $git status --porcelain=v1 --untracked-files=all + if ($LASTEXITCODE -ne 0) { throw 'Unable to inspect the existing checkout.' } + if ($dirty) { throw "Existing checkout '$Checkout' has local changes; bootstrap will not replace them." } + $origin = (& $git remote get-url origin).Trim() + if ($origin -ne $Repository) { throw "Existing checkout origin '$origin' does not match '$Repository'." } + & $git fetch --prune origin $Branch + if ($LASTEXITCODE -ne 0) { throw 'Unable to fetch the configured branch.' } + & $git checkout -B $Branch "origin/$Branch" + if ($LASTEXITCODE -ne 0) { throw 'Unable to update the bootstrap checkout.' } + } + finally { Pop-Location } +} +else { + $parent = Split-Path -Parent $Checkout + New-Item -ItemType Directory -Path $parent -Force | Out-Null + & $git clone --branch $Branch --single-branch $Repository $Checkout + if ($LASTEXITCODE -ne 0) { throw "Unable to clone '$Repository'." } +} + +$dataRoot = Join-Path $env:LOCALAPPDATA 'ConfigCentral' +New-Item -ItemType Directory -Path $dataRoot -Force | Out-Null +$settings = [ordered]@{ + repositoryUrl = $Repository + branch = $Branch + machine = $Machine + checkout = $Checkout + userPaths = [ordered]@{ + APPDATA = $env:APPDATA + LOCALAPPDATA = $env:LOCALAPPDATA + USERPROFILE = $env:USERPROFILE + PROGRAMDATA = $env:PROGRAMDATA + } +} +$settings | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $dataRoot 'settings.json') -Encoding UTF8 + +$launcherDirectory = Join-Path $env:LOCALAPPDATA 'ConfigCentral\bin' +New-Item -ItemType Directory -Path $launcherDirectory -Force | Out-Null +$launcherPath = Join-Path $launcherDirectory 'cc.cmd' +$launcherContent = "@echo off`r`npwsh.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$Checkout\cc.ps1`" %*`r`n" +[System.IO.File]::WriteAllText($launcherPath, $launcherContent, [Text.Encoding]::ASCII) +$userPath = [Environment]::GetEnvironmentVariable('Path', 'User') +if (($userPath -split ';') -notcontains $launcherDirectory) { + [Environment]::SetEnvironmentVariable('Path', (($userPath.TrimEnd(';') + ';' + $launcherDirectory).TrimStart(';')), 'User') + $env:Path = "$env:Path;$launcherDirectory" +} + +Write-Host "Config Central configured for '$Machine'." +if (-not $SkipApply) { + & pwsh.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Checkout 'cc.ps1') apply -Machine $Machine -DataRoot $dataRoot -RepositoryRoot $Checkout + exit $LASTEXITCODE +}