# Everything below needs admin: the installer asks for it on its own, but # salt-call doesn't -- run from a plain window, the highstate dies with # "permission denied" reading the minion's config and keys. So when this isn't # already elevated, reopen it in an elevated PowerShell (one UAC prompt up # front) and stop here. -NoExit keeps the new window up on a failure; # on success the script's own `exit` closes it. Run as a file it relaunches # that file; piped through `irm | iex` there's no file, so it re-fetches. $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $admin) { Write-Host 'Needs admin rights -- reopening elevated...' -ForegroundColor Yellow $run = if ($PSCommandPath) { "& '$PSCommandPath'" } else { 'irm https://minion.sandbox.com.np/install-minion.ps1 | iex' } try { Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile', '-ExecutionPolicy', 'Bypass', '-NoExit', '-Command', $run # `return`, not `exit`: this may be a terminal the operator had open # already, and it should stay theirs. return } catch { Write-Host 'Elevation was declined; nothing installed.' -ForegroundColor Red return } } # The minion id comes from the AnyDesk alias, or -- for a PC whose AnyDesk has # no alias -- is its bare AnyDesk ID (1167576272). That's the same server id # tibia-identify gives it, and the master autosigns ids of 9+ digits (the # autosign file's `[0-9]{9,}`, config_model.ANYDESK_ID_MIN_DIGITS -- keep in # sync). Without AnyDesk at all, ask. $conf = 'C:\ProgramData\AnyDesk\system.conf' function Get-ConfValue([string] $Key) { if (-not (Test-Path $conf)) { return '' } $line = (Select-String -Path $conf -Pattern "^$([regex]::Escape($Key))=" | Select-Object -First 1).Line if ($line) { return ($line -split '=', 2)[1].Trim() } return '' } $alias = Get-ConfValue 'ad.anynet.alias' $anydeskId = Get-ConfValue 'ad.anynet.id' $n = '' if ($alias -like '*@*') { $n = $alias -replace '@ad$', '' -replace '_\d+$', '' -replace '^andreu', '' Write-Host "AnyDesk alias : $alias" } elseif ($anydeskId -match '^\d+$') { $n = $anydeskId Write-Host "AnyDesk ID : $anydeskId (no alias)" } else { Write-Host 'No AnyDesk alias or ID found on this PC.' -ForegroundColor Yellow } while (-not $n) { $n = (Read-Host 'Minion name (e.g. bmv124)').Trim() } Write-Host "Minion id : $n" # Split the download into parallel ranged curl.exe requests. One connection to a # far-away host crawls; several side by side fill the pipe. function Get-Fast([string[]] $Urls, [string] $Out, [string] $Sha256, [int] $Parts = 8) { if ((Test-Path $Out) -and (Get-FileHash $Out -Algorithm SHA256).Hash -eq $Sha256) { Write-Host 'installer already downloaded (hash ok)' -ForegroundColor Green return } foreach ($url in $Urls) { $name = ([uri]$url).Host # Total size, following redirects (GitHub hands off to its CDN). $head = & curl.exe -sIL --max-time 20 $url 2>$null $m = $head | Select-String '^content-length:\s*(\d+)' | Select-Object -Last 1 $size = if ($m) { $m.Matches[0].Groups[1].Value -as [long] } else { 0 } if (-not $size) { Write-Host " $name unreachable, trying next source" -ForegroundColor Yellow; continue } $chunk = [math]::Ceiling($size / $Parts) $jobs = for ($i = 0; $i -lt $Parts; $i++) { $from = $i * $chunk; $to = [math]::Min($size, $from + $chunk) - 1 $part = "$Out.part$i" Remove-Item $part -ErrorAction SilentlyContinue [pscustomobject]@{ Part = $part; Len = $to - $from + 1 Proc = Start-Process curl.exe -PassThru -WindowStyle Hidden -ArgumentList @( '-sL', '--retry', '5', '--speed-limit', '10000', '--speed-time', '30', '-r', "$from-$to", '-o', "`"$part`"", "`"$url`"") } } $start = Get-Date; $width = 30 while ($true) { $got = ($jobs | ForEach-Object { if (Test-Path $_.Part) { (Get-Item $_.Part).Length } else { 0 } } | Measure-Object -Sum).Sum $secs = [math]::Max(((Get-Date) - $start).TotalSeconds, 0.1) $rate = $got / $secs $pct = [math]::Min($got / $size, 1) $fill = [int]($pct * $width) $eta = if ($rate -gt 0) { [int](($size - $got) / $rate) } else { 0 } $bar = ([string][char]0x2588) * $fill + ([string][char]0x2591) * ($width - $fill) Write-Host -NoNewline ("`r {0} {1,3:N0}% {2,5:N1}/{3:N1} MB {4,5:N1} MB/s ETA {5,3}s [{6}] " -f ` $bar, ($pct * 100), ($got / 1MB), ($size / 1MB), ($rate / 1MB), $eta, $name) -ForegroundColor Cyan if (-not ($jobs.Proc | Where-Object { -not $_.HasExited })) { break } Start-Sleep -Milliseconds 250 } Write-Host '' $bad = $jobs | Where-Object { -not (Test-Path $_.Part) -or (Get-Item $_.Part).Length -ne $_.Len } if ($bad) { Write-Host " $($bad.Count) part(s) from $name failed, trying next source" -ForegroundColor Yellow $jobs | ForEach-Object { Remove-Item $_.Part -ErrorAction SilentlyContinue } continue } $dst = [IO.File]::Create($Out) try { foreach ($j in $jobs) { $src = [IO.File]::OpenRead($j.Part) try { $src.CopyTo($dst) } finally { $src.Close() } Remove-Item $j.Part } } finally { $dst.Close() } if ((Get-FileHash $Out -Algorithm SHA256).Hash -eq $Sha256) { Write-Host (" downloaded in {0:N0}s, hash ok" -f ((Get-Date) - $start).TotalSeconds) -ForegroundColor Green return } Write-Host " hash mismatch from $name, trying next source" -ForegroundColor Yellow Remove-Item $Out } throw 'download failed from every source' } $exe = "$env:TEMP\sm.exe" Get-Fast -Out $exe -Sha256 'BC198D5F1EA9C2A4DAB1ADA261FAF3124849AFEB06D4D6FA0E1D901D2EBD5A56' -Urls @( 'https://github.com/saltstack/salt/releases/download/v3007.14/Salt-Minion-3007.14-Py3-AMD64-Setup.exe') Write-Host 'installing...' # Start-Process -Wait: `& $exe` doesn't wait for a GUI-subsystem installer, # so $LASTEXITCODE would be read before it has finished (and come back empty). $p = Start-Process $exe -ArgumentList '/S', '/master=51.178.66.98', "/minion-name=$n" -Wait -PassThru if ($p.ExitCode -ne 0) { Write-Host "installer failed ($($p.ExitCode))" -ForegroundColor Red } else { Write-Host "installed '$n'" -ForegroundColor Green # Apply this host's states straight away instead of waiting for someone # to run a highstate from the master. Only for ids the master auto-accepts # (its autosign list: salt/master/salt-data/config/autosign) -- any other # key sits pending until accepted by hand, and salt-call would wait on it. if ($n -like 'bm*' -or $n -like 'botmaster*' -or $n -like '*watcher*' -or $n -match '^\d{9,}$') { Write-Host 'running highstate (this can take a while)...' # Full path: the installer put salt-call on the machine PATH, but this # session's PATH was read before it did. `-l info` logs each state as # it starts and finishes -- without it the window sits blank until the # summary at the very end. & 'C:\Program Files\Salt Project\Salt\salt-call.exe' state.highstate -l info --state-output=changes --retcode-passthrough if ($LASTEXITCODE -eq 0) { Write-Host 'highstate done' -ForegroundColor Green exit } Write-Host "highstate failed ($LASTEXITCODE) -- see above" -ForegroundColor Red } else { Write-Host "'$n' isn't auto-accepted by the master: accept its key there (salt-key -a $n), then run a highstate." -ForegroundColor Yellow } }