#!/usr/bin/env pwsh #Requires -Version 5.1 # Stop on errors $ErrorActionPreference = "Stop" # Colors for output $RED = "Red" $GREEN = "Green" $YELLOW = "Yellow" $GITHUB_USER = "what386" $GITHUB_REPO = "upstream-rs" $BINARY_NAME = "upstream" $UPSTREAM_DIR = Join-Path $HOME ".upstream" function Write-ColorOutput { param( [string]$Message, [string]$Color = "", [switch]$NoNewline ) $params = @{} if ($Color) { $params["ForegroundColor"] = $Color } if ($NoNewline) { $params["NoNewline"] = $true } Write-Host $Message @params } function Detect-Arch { # Try multiple methods to detect architecture # Method 1: Using RuntimeInformation when available. try { $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture switch ($arch) { ([System.Runtime.InteropServices.Architecture]::X64) { return "x86_64" } ([System.Runtime.InteropServices.Architecture]::Arm64) { return "aarch64" } } } catch { # Fall back to environment and WMI/CIM probes below. } $envArch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } switch ($envArch) { "AMD64" { return "x86_64" } "ARM64" { return "aarch64" } } try { $wmiArch = (Get-CimInstance -ClassName Win32_Processor | Select-Object -First 1).Architecture switch ($wmiArch) { 9 { return "x86_64" } # x64 12 { return "aarch64" } # ARM64 } } catch { try { $wmiArch = (Get-WmiObject -Class Win32_Processor | Select-Object -First 1).Architecture switch ($wmiArch) { 9 { return "x86_64" } # x64 12 { return "aarch64" } # ARM64 } } catch { # Unsupported or unavailable probe. } } return "unknown" } function Get-VisualCppRuntimeArchitecture { param( [string]$Architecture ) switch ($Architecture) { "x86_64" { return "x64" } "aarch64" { return "arm64" } default { throw "Unsupported Visual C++ runtime architecture: $Architecture" } } } function Test-VisualCppRuntimeInstalled { param( [string]$Architecture ) $runtimeArchitecture = Get-VisualCppRuntimeArchitecture -Architecture $Architecture $registryPaths = @( "HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\$runtimeArchitecture", "HKLM:\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\$runtimeArchitecture" ) foreach ($registryPath in $registryPaths) { try { $runtime = Get-ItemProperty -LiteralPath $registryPath -ErrorAction Stop if ($runtime.Installed -eq 1) { return $true } } catch { # The runtime may be registered in the other registry view. } } return $false } function Install-VisualCppRuntimeIfMissing { param( [string]$Architecture ) if (Test-VisualCppRuntimeInstalled -Architecture $Architecture) { return } $runtimeArchitecture = Get-VisualCppRuntimeArchitecture -Architecture $Architecture $downloadUrl = "https://aka.ms/vc14/vc_redist.$runtimeArchitecture.exe" $tempDirectory = $null Write-ColorOutput "Microsoft Visual C++ Redistributable ($runtimeArchitecture) is missing. Downloading it from Microsoft..." $YELLOW Write-Host "Windows will ask for administrator approval to install this prerequisite. Upstream itself will stay in your user account." try { $tempDirectory = New-Item -ItemType Directory -Path ([System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [System.IO.Path]::GetRandomFileName())) $runtimeInstaller = Join-Path $tempDirectory "vc_redist.$runtimeArchitecture.exe" Invoke-WebRequest -Uri $downloadUrl -OutFile $runtimeInstaller -UseBasicParsing $signature = Get-AuthenticodeSignature -LiteralPath $runtimeInstaller if ($signature.Status -ne "Valid" -or $signature.SignerCertificate.Subject -notmatch '(?:^|,\s*)CN=Microsoft Corporation(?:,|$)') { throw "The downloaded runtime installer does not have a valid Microsoft signature." } # Elevate only Microsoft's installer, leaving the rest of setup unelevated. $process = Start-Process -FilePath $runtimeInstaller -ArgumentList @("/install", "/passive", "/norestart") -Verb RunAs -Wait -PassThru -ErrorAction Stop if ($process.ExitCode -notin @(0, 3010)) { throw "The runtime installer exited with code $($process.ExitCode)." } if ($process.ExitCode -eq 3010) { Write-ColorOutput "The runtime was installed, but Windows reports that a restart is required. Restart if Upstream cannot start." $YELLOW } if (-not (Test-VisualCppRuntimeInstalled -Architecture $Architecture)) { throw "The $runtimeArchitecture runtime was not detected after installation. A Windows restart may be required." } Write-ColorOutput "Microsoft Visual C++ Redistributable installed. Continuing Upstream installation..." $GREEN } catch { throw @" Could not install Microsoft Visual C++ Redistributable ($runtimeArchitecture): $_ Install the latest supported Visual C++ Redistributable from Microsoft: https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist Then rerun this installer. "@ } finally { if ($tempDirectory -and (Test-Path -LiteralPath $tempDirectory)) { Remove-Item -LiteralPath $tempDirectory -Recurse -Force } } } function Confirm-Checksum { param( [string]$Binary, [string]$ChecksumFile, [string]$AssetName ) $expected = $null foreach ($line in Get-Content -LiteralPath $ChecksumFile) { if ($line -match '^([A-Fa-f0-9]{64})\s+\*?(.+)$' -and $Matches[2] -eq $AssetName) { $expected = $Matches[1] break } } if (-not $expected) { throw "No checksum found for $AssetName." } $actual = (Get-FileHash -LiteralPath $Binary -Algorithm SHA256).Hash if (-not $actual.Equals($expected, [System.StringComparison]::OrdinalIgnoreCase)) { throw "Checksum verification failed for $AssetName." } } function Select-ExistingDataAction { if (-not (Test-Path $UPSTREAM_DIR)) { return "new" } if (-not (Test-Path $UPSTREAM_DIR -PathType Container)) { throw "'$UPSTREAM_DIR' exists but is not a directory." } if ($env:UPSTREAM_EXISTING_DATA) { switch ($env:UPSTREAM_EXISTING_DATA.ToLowerInvariant()) { "keep" { return "keep" } "replace" { return "replace" } default { throw "UPSTREAM_EXISTING_DATA must be 'keep' or 'replace'." } } } if ([Console]::IsInputRedirected) { Write-ColorOutput "Existing '$UPSTREAM_DIR' found; no interactive input available, keeping it." $YELLOW return "keep" } while ($true) { $answer = Read-Host "Existing '$UPSTREAM_DIR' found. Keep it and refresh hooks, or replace it? [K/r]" switch ($answer.ToLowerInvariant()) { "" { return "keep" } "k" { return "keep" } "keep" { return "keep" } "r" { return "replace" } "replace" { return "replace" } default { Write-Host "Please answer 'keep' or 'replace'." } } } } function Invoke-UpstreamCommand { param( [string]$Binary, [string[]]$Arguments ) Write-ColorOutput "Running: " $YELLOW -NoNewline Write-Host "upstream $($Arguments -join ' ')" & $Binary @Arguments if ($LASTEXITCODE -ne 0) { throw "Command failed: upstream $($Arguments -join ' ')" } } function Test-UpstreamPackageInstalled { param( [string]$Binary ) $output = & $Binary @("list", "--json") 2>$null if ($LASTEXITCODE -ne 0) { return $false } try { $packages = @($output | ConvertFrom-Json) } catch { return $false } return [bool]($packages | Where-Object { $_.id -eq "upstream" } | Select-Object -First 1) } function Install-UpstreamIfMissing { param( [string]$Binary ) if (Test-UpstreamPackageInstalled -Binary $Binary) { Write-ColorOutput "Managed upstream package already present; skipping package install." $GREEN } else { Invoke-UpstreamCommand -Binary $Binary -Arguments @("--yes", "install", "what386/upstream-rs", "-k", "win-exe") } } function Main { Write-ColorOutput "Starting installation..." $GREEN $ARCH = Detect-Arch if ($ARCH -eq "unknown") { Write-ColorOutput "Error: Unsupported architecture" $RED Write-Host "Debug info:" Write-Host " PROCESSOR_ARCHITECTURE: $env:PROCESSOR_ARCHITECTURE" Write-Host " PROCESSOR_ARCHITEW6432: $env:PROCESSOR_ARCHITEW6432" try { Write-Host " RuntimeInformation: $([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)" } catch { Write-Host " RuntimeInformation: Not available" } exit 1 } Write-Host "Detected Architecture: $ARCH" try { Install-VisualCppRuntimeIfMissing -Architecture $ARCH } catch { Write-ColorOutput "Error: $_" $RED exit 1 } $ASSET_NAME = "${BINARY_NAME}-${ARCH}-pc-windows-msvc.exe" $DOWNLOAD_URL = "https://github.com/${GITHUB_USER}/${GITHUB_REPO}/releases/latest/download/${ASSET_NAME}" $CHECKSUM_URL = "https://github.com/${GITHUB_USER}/${GITHUB_REPO}/releases/latest/download/SHA256SUMS.txt" Write-Host "Downloading from: $DOWNLOAD_URL" # Create temporary directory $TMP_DIR = New-Item -ItemType Directory -Path ([System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [System.IO.Path]::GetRandomFileName())) $TMP_FILE = Join-Path $TMP_DIR "${BINARY_NAME}.exe" $CHECKSUM_FILE = Join-Path $TMP_DIR "SHA256SUMS.txt" try { # Download file Invoke-WebRequest -Uri $DOWNLOAD_URL -OutFile $TMP_FILE -UseBasicParsing Invoke-WebRequest -Uri $CHECKSUM_URL -OutFile $CHECKSUM_FILE -UseBasicParsing Confirm-Checksum -Binary $TMP_FILE -ChecksumFile $CHECKSUM_FILE -AssetName $ASSET_NAME Write-ColorOutput "Download complete!" $GREEN $existingAction = Select-ExistingDataAction if ($existingAction -eq "replace") { Write-ColorOutput "Removing existing '$UPSTREAM_DIR'..." $YELLOW Remove-Item -Recurse -Force $UPSTREAM_DIR } elseif ($existingAction -eq "keep") { Write-ColorOutput "Keeping existing '$UPSTREAM_DIR'." $GREEN } Invoke-UpstreamCommand -Binary $TMP_FILE -Arguments @("hooks", "init") Install-UpstreamIfMissing -Binary $TMP_FILE Write-ColorOutput "Installation complete!" $GREEN } catch { Write-ColorOutput "Error: $_" $RED exit 1 } finally { if (Test-Path $TMP_DIR) { Remove-Item -Recurse -Force $TMP_DIR } } } # Run main function Main