Files
nixos-setup/bin/lib/cmds.nu
T
2026-09-26 01:47:42 -04:00

610 lines
21 KiB
Nu

use types.nu *
use profile.nu *
use helpers.nu *
export def skyg [] {
print $REPO_ROOT
let subcmds = (help commands |
where name starts-with "skyg " |
each {|c| $c.name | split row " " | get 1 } |
uniq | str join ', ')
print $"Subcommands: ($subcmds)"
print "Run: skyg <subcommand> --help"
}
export def "skyg profiles" [only_remote: bool = false] {
if $only_remote {
valid_remote_profiles | print
} else {
valid_profiles | print
}
}
export def "skyg check" [] {
nix flake check --no-build
}
# Validate that all versioned flake inputs use the same NixOS release
export def "skyg check-flake-versions" [] {
let flake = "flake.nix"
if not ($flake | path exists) {
print "check-flake-versions: flake.nix not found, skipping"
return
}
# Only scan url lines to avoid false positives from embedded script strings
let url_lines = (open $flake | lines | enumerate | where { |row|
($row.item | str contains "url") and ($row.item =~ 'release-\d+\.\d+')
})
let versions = ($url_lines
| each {|row| $row.item | parse --regex '.*release-(?P<version>\d+\.\d+).*' | get version }
| flatten
| uniq)
if ($versions | length) <= 1 {
print "check-flake-versions: OK"
return
}
print "check-flake-versions: mismatched NixOS release versions in flake.nix:"
print ""
for version in $versions {
print $" release-($version):"
$url_lines | where {|row| $row.item | str contains $"release-($version)" } | each { |row|
print $" line ($row.index + 1): ($row.item | str trim)"
}
}
print ""
print "All versioned inputs (home-manager, stylix, etc.) must use the same NixOS release."
error make {msg: "Mismatched NixOS release versions"}
}
# rollback configuration
export def "skyg rollback" [] {
sudo nixos-rebuild switch --rollback
}
# update some flakes
export def "skyg update" [input_name: string = ""] {
cd $REPO_ROOT
if $input_name == "" {
print "Updating all flakes..."
nix flake update | print
} else {
print $"Updating flake: ($input_name)"
nix flake update $input_name | print
}
git diff flake.lock | print
}
# Build local os
export def "skyg os" [cmd: string, --build-host: string = ""] {
cd $REPO_ROOT
mut runcmd = $"nh os ($cmd)"
if $build_host != "" {
$runcmd = $"($runcmd) --build-host ($build_host).lab.internal"
}
$runcmd | print
bash -c $runcmd
}
# Deploy to remote machine
export def "skyg remote" [
cmd: string@remote-cmds,
target: string@remote_targets = "",
--build-host: string@remote_targets = "", # Optional remote builder host (e.g. builder.lab.internal)
] {
cd $REPO_ROOT
mut target_host = $"root@($target).lab.internal"
mut profile = $"hl-($target)"
if not (is-valid-profile $profile true) {
print $"Invalid Remote Profile '(ansi green_bold)($target)(ansi reset)', please select one of:"
return (remote_targets)
}
$"Using [(ansi green_bold)($profile)(ansi reset)]" | print
$"($cmd) on ($target_host) with ($profile)" | print
mut runcmd = $"nh os ($cmd) --target-host ($target_host) --ask .#($profile)"
if $build_host != "" {
$runcmd = $"($runcmd) --build-host ($build_host).lab.internal"
}
$runcmd | print
bash -c $runcmd
}
# Fresh-install a remote machine via nixos-anywhere, using its disko config.
# Always reformats every disk in the disko file — a second run is as destructive as the first.
# Missing disko file, live disk OS (without --force-wipe), or mistyped hostname all abort.
export def "skyg remote install" [
target: string@remote_targets,
--force-wipe, # wipe even if the host already runs NixOS from disk
] {
cd $REPO_ROOT
let target_host = $"root@($target).lab.internal"
let profile = $"hl-($target)"
if not (is-valid-profile $profile true) {
print $"Invalid Remote Profile '(ansi green_bold)($target)(ansi reset)', please select one of:"
return (remote_targets)
}
let disko_file = $"hosts/($profile).disko.nix"
if not ($disko_file | path exists) {
error make {msg: $"Missing disko config: ($disko_file). Refusing to install ($profile) without a disko layout."}
}
print ""
print $"(ansi red_bold)WARNING: this WIPES every disk listed in ($disko_file).(ansi reset)"
print "This is not a switch. Use `skyg remote switch` / `skyg remote boot` to update an installed host."
print ""
print "Disks in the disko file:"
let disks = (
open $disko_file
| lines
| where {|l| ($l | str contains "device") and ($l | str contains "=") }
| each {|l| $l | str trim }
)
for line in $disks {
print $" ($line)"
}
print ""
let ssh = $"ssh -o BatchMode=yes -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new ($target_host)"
let root_fstype = (try {
bash -c $"($ssh) 'findmnt -n -o FSTYPE /' 2>/dev/null" | str trim
} catch { "" })
if $root_fstype == "" {
print $"(ansi yellow)Could not SSH to ($target_host) to check for a live OS.(ansi reset)"
} else {
print $"Remote / fstype: ($root_fstype)"
let installer_fs = ["overlay" "tmpfs" "squashfs"]
if not ($root_fstype in $installer_fs) {
if not $force_wipe {
error make {msg: $"($target_host) already boots from disk (root fstype ($root_fstype)). Refusing to wipe. Use `skyg remote switch ($target)` to update, or pass --force-wipe to reinstall."}
}
print $"(ansi yellow)--force-wipe set: proceeding against a live disk OS.(ansi reset)"
} else {
print "Remote looks like an installer live image (ok to install)."
}
}
let confirm = input $"Type ($target) to continue: " | str trim
if $confirm != $target {
error make {msg: $"Aborted: typed '($confirm)', expected '($target)'."}
}
$"Installing [(ansi green_bold)($profile)(ansi reset)] on ($target_host) via nixos-anywhere, using ($disko_file)" | print
let runcmd = $"nix run github:nix-community/nixos-anywhere -- --flake .#($profile) ($target_host)"
$runcmd | print
let bash_path = which bash | get 0.path
with-env { SHELL: $bash_path } {
bash -c $runcmd
}
}
# Boot all remote hosts except the current machine (fwbook)
# Checks online status first, runs `skyg remote boot --build-host fwdesk <host>` for each online host,
# and writes a summary report to .tmp/boot-report.txt
export def "skyg remote boot-all" [] {
cd $REPO_ROOT
mkdir .tmp
let current_host = "fwbook"
let report_file = ".tmp/boot-report.txt"
# Discover remote targets from the flake (same logic as skyg remote)
let all_hosts = remote_targets | where {|h| $h != $current_host }
print $"Found ($all_hosts | length) candidate hosts excluding ($current_host)"
mut successes = []
mut failures = []
mut skipped = []
# Phase 1: sequential SSH reachability checks (fast)
mut online_hosts = []
for host in $all_hosts {
print $"\n=== Checking ($host) ==="
let target = $"root@($host).lab.internal"
let is_online = (try {
bash -c $"ssh -o BatchMode=yes -o ConnectTimeout=3 -o StrictHostKeyChecking=accept-new ($target) 'true' >/dev/null 2>&1"
true
} catch { false })
if not $is_online {
print $"(ansi yellow)OFFLINE(ansi reset): ($host)"
$skipped = ($skipped | append $host)
} else {
print $"(ansi green)ONLINE(ansi reset): ($host)"
$online_hosts = ($online_hosts | append $host)
}
}
# Phase 2: run boots in parallel (2 concurrent) without interactive prompts
if ($online_hosts | length) > 0 {
print "
Starting parallel boots (concurrency: 2)..."
let boot_results = ($online_hosts | par-each --threads 1 { |host|
let target_host = $"root@($host).lab.internal"
let profile = $"hl-($host)"
let runcmd = $"nh os boot --target-host ($target_host) .#($profile)"
print $runcmd
let ok = (try {
bash -c $runcmd
true
} catch {
false
})
{host: $host, success: $ok}
})
for r in $boot_results {
if $r.success {
$successes = ($successes | append $r.host)
print $"(ansi green)SUCCESS(ansi reset): ($r.host)"
} else {
$failures = ($failures | append $r.host)
print $"(ansi red)FAILED(ansi reset): ($r.host)"
}
}
}
# Write report
let timestamp = date now | format date "%Y-%m-%d %H:%M:%S"
let report = $"Boot Report - ($timestamp)
Total hosts considered: ($all_hosts | length)
Skipped offline: ($skipped | length) - ($skipped | str join ', ')
Successful: ($successes | length) - ($successes | str join ', ')
Failed: ($failures | length) - ($failures | str join ', ')
Details:
Online & Booted: ($successes | str join ', ')
Offline: ($skipped | str join ', ')
Failed: ($failures | str join ', ')
"
$report | save -f $report_file
print $"
Report written to ($report_file)"
print $report
}
# Check status of all remotes: generation, pending reboot, needs rebuild
export def "skyg remote status" [] {
cd $REPO_ROOT
mkdir .tmp
let current_host = "fwbook"
let report_file = ".tmp/status-report.txt"
let all_hosts = remote_targets | where {|h| $h != $current_host }
print $"Checking status for ($all_hosts | length) remotes..."
let results = ($all_hosts | each { |host|
print $"
=== ($host) ==="
let target = $"root@($host).lab.internal"
let online = (try {
bash -c $"ssh -o BatchMode=yes -o ConnectTimeout=3 ($target) 'true' >/dev/null 2>&1"
true
} catch { false })
if not $online {
print $"(ansi yellow)OFFLINE(ansi reset)"
return {host: $host, status: "offline", booted: "", current: "", reboot_pending: false, needs_build: false}
}
let info = (try {
let booted = bash -c $"ssh ($target) 'readlink /run/booted-system' 2>/dev/null" | str trim
let current = bash -c $"ssh ($target) 'readlink /run/current-system' 2>/dev/null" | str trim
let reboot_pending = ($booted != $current)
# Compare what the local flake currently evaluates to vs remote's active system
let local_toplevel = (try {
(bash -c $"nix eval --raw '.#hl-($host).config.system.build.toplevel.outPath' 2>/dev/null || true") | str trim
} catch { "" })
let needs_build = if $local_toplevel == "" { false } else { $local_toplevel != $current }
{host: $host, status: "online", booted: $booted, current: $current, reboot_pending: $reboot_pending, needs_build: $needs_build}
} catch {
{host: $host, status: "error", booted: "", current: "", reboot_pending: false, needs_build: false}
})
print $"Booted: ($info.booted | path basename)"
print $"Current: ($info.current | path basename)"
if $info.reboot_pending {
print $"(ansi yellow)REBOOT PENDING(ansi reset)"
}
if $info.needs_build {
print $"(ansi red)NEEDS NEW BUILD(ansi reset)"
} else {
print $"(ansi green)UP TO DATE(ansi reset)"
}
$info
})
let timestamp = date now | format date "%Y-%m-%d %H:%M:%S"
let lines = ($results | each { |r|
if $r.status == "offline" {
$"- ($r.host): (ansi yellow)OFFLINE(ansi reset)"
} else if $r.status == "error" {
$"- ($r.host): (ansi red)ERROR querying status(ansi reset)"
} else {
let pending = if $r.reboot_pending { $" [(ansi blue)REBOOT PENDING(ansi reset)]" } else { "" }
let build = if $r.needs_build { $" [(ansi red)NEEDS REBUILD(ansi reset)]" } else { $" [(ansi green)current(ansi reset)]" }
$"- ($r.host): booted=($r.booted | path basename) current=($r.current | path basename)($pending)($build)"
}
})
let report = $"Remote Status Report - ($timestamp)
" + ($lines | str join "
") + "
"
$report | save -f $report_file
print $"
Report written to ($report_file)"
print $report
}
# Deploy OpenWrt router configuration
export def "skyg openwrt" [
router: string = "glmain",
--dry-run # Render configs to .tmp/openwrt-<router>/ without touching the router
] {
cd $REPO_ROOT
let decrypted_file = skyg decrypt $"($router).json"
if $dry_run {
^cat $decrypted_file | nix run .#openwrt-($router)-dry-run -- ($router)
} else {
^cat $decrypted_file | nix run .#openwrt-($router)
}
}
# Build a bootable image: ISO, or Pi SD card image (fully-baked, no on-device rebuild)
export def "skyg build-image" [target: string] {
cd $REPO_ROOT
let spec = (match $target {
"iso" => { config: "iso", out: "iso", attr: "isoImage" }
"pi1" => { config: "hl-pi1", out: "sd-image", attr: "sdImage" }
"pi2" => { config: "hl-pi2", out: "sd-image", attr: "sdImage" }
_ => { error make { msg: $"Unknown image target '($target)'. Expected: iso, pi1, pi2" } }
})
let imageBuildTime = date now | format date "%Y.%m.%d_%H_%M_%S"
let rootOutputFolder = $REPO_ROOT | path join "build" $spec.config
let outPutFolder = $rootOutputFolder | path join $imageBuildTime
rm -rf $rootOutputFolder
mkdir $rootOutputFolder
nix build $"#nixosConfigurations.($spec.config).config.system.build.($spec.attr)" -o $outPutFolder
printf $outPutFolder
}
# Home Manager operations
export def "skyg hm" [action: string, profile: string = "ari"] {
cd $REPO_ROOT
$"Running home-manager ($action) for profile ($profile)" | print
home-manager $action --flake $".#($profile)"
}
# List all secret names
export def "skyg secrets" [] {
secret-names
}
# Decrypt a secret from secrets/ folder
export def "skyg decrypt" [secret: string] {
cd $REPO_ROOT
let src = $"secrets/($secret).age"
if not ($src | path exists) {
error make {msg: $"Secret not found: ($src)"}
}
mkdir .tmp
let dest = $".tmp/unencrypted-($secret)"
agenix -d $src | save -f $dest
print $"Decrypted to ($dest)"
return $dest
}
# Encrypt a file to secrets/ folder (re-encrypts using agenix)
# --yaml Validate the content as YAML (via yq) before encrypting
export def "skyg encrypt" [
secret: string@secret-names,
source?: string,
--yaml # Validate the content as YAML (via yq) before encrypting
] {
cd $REPO_ROOT
let src = $source | default $".tmp/unencrypted-($secret)"
if not ($src | path exists) {
let encrypted = $"secrets/($secret).age"
if ($encrypted | path exists) {
agenix -d $encrypted | save -f $src
} else {
touch $src
}
}
vi $src
if $yaml {
# `complete` captures stdout/stderr/exit_code; `try/catch` guards a missing yq
let lint = (
try {
yq e '.' $src | complete
} catch { null }
)
if $lint == null {
print $"❌ Could not run yq — is it on PATH? Add 'yq' to the devShell in flake.nix."
return
}
if $lint.exit_code != 0 {
print $"❌ YAML validation failed for ($src):"
print ($lint.stderr | str trim)
print $"Fix the syntax, then re-run: skyg encrypt ($secret) --yaml"
return
}
print $"✅ YAML valid: ($src)"
}
let dest = $"secrets/($secret).age"
cat $src | agenix -e $dest
print $"Encrypted ($dest)"
return $dest
}
# Compare unencrypted local version with encrypted version of a secret
export def "skyg compare-secret" [secret: string@secret-names] {
cd $REPO_ROOT
let unencrypted = $".tmp/unencrypted-($secret)"
let encrypted = $"secrets/($secret).age"
let temp_decrypted = $"/tmp/skyg-compare-($secret)-($env.USER)-(random uuid)"
agenix -d $encrypted | save -f $temp_decrypted
print $"Comparing ($unencrypted) with decrypted ($encrypted)"
try {
print $"diff -u $(unencrypted) $(temp_decrypted)"
diff -u $unencrypted $temp_decrypted | print
} catch {
print "Files are identical"
}
rm -f $temp_decrypted
}
# Generate the lab root CA: key encrypted to secrets/lab-ca-key.age,
# public cert written to configs/pki/lab-ca.crt. Run once, before `ca issue`.
export def "skyg ca init" [
--days: int = 3650 # CA lifetime in days
] {
cd $REPO_ROOT
let cert = "configs/pki/lab-ca.crt"
let key_secret = "secrets/lab-ca-key.age"
if ($cert | path exists) {
error make {msg: $"($cert) already exists — refusing to overwrite the CA. Delete it manually to rotate."}
}
ensure-secret-entry $key_secret ["ari"]
mkdir .tmp configs/pki
let tmp_key = ".tmp/lab-ca-key.pem"
(openssl req -x509 -newkey rsa:4096 -sha256 -days $days -nodes
-keyout $tmp_key -out $cert
-subj "/CN=Skyg Lab CA"
-addext "basicConstraints=critical,CA:TRUE"
-addext "keyUsage=critical,keyCertSign,cRLSign")
^cat $tmp_key | agenix -e $key_secret
rm -f $tmp_key
print $"✅ CA cert: ($cert) — commit this"
print $"✅ CA key encrypted: ($key_secret)"
print "Next: skyg ca issue <domain> --for <host>"
}
# Issue a TLS cert for a domain, signed by the lab CA.
# Writes configs/pki/<domain>.crt; encrypts the key to secrets/<name>-tls-key.age.
export def "skyg ca issue" [
domain: string # e.g. buzz.app.internal
--for: string # secrets.nix key name allowed to decrypt the leaf key (e.g. minipc1)
--days: int = 825 # leaf lifetime (825 = browser max)
--name: string # secret slug override (default: first DNS label)
] {
cd $REPO_ROOT
let ca_cert = "configs/pki/lab-ca.crt"
let ca_key_secret = "secrets/lab-ca-key.age"
if not ($ca_cert | path exists) {
error make {msg: "No CA found — run `skyg ca init` first"}
}
let key_names = (^cat secrets.nix | parse --regex '(\w+) = "ssh-' | get capture0)
if ($for not-in $key_names) {
error make {msg: $"Unknown recipient '($for)'. Known: ($key_names | str join ', ')"}
}
let slug = $name | default ($domain | split row "." | first)
let secret = $"secrets/($slug)-tls-key.age"
let cert = $"configs/pki/($domain).crt"
if ($cert | path exists) {
error make {msg: $"($cert) already exists — delete it manually to re-issue."}
}
ensure-secret-entry $secret ["ari" $for]
mkdir .tmp configs/pki
let ca_key = ".tmp/lab-ca-key.pem"
agenix -d $ca_key_secret | save -f $ca_key
let leaf_key = $".tmp/($slug)-tls-key.pem"
let csr = $".tmp/($slug).csr"
let ext = $".tmp/($slug)-ext.cnf"
$"basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:($domain)\n" | save -f $ext
(openssl req -newkey rsa:2048 -nodes
-keyout $leaf_key -out $csr
-subj $"/CN=($domain)")
(openssl x509 -req -in $csr
-CA $ca_cert -CAkey $ca_key -CAcreateserial
-out $cert -days $days -sha256 -extfile $ext)
^cat $leaf_key | agenix -e $secret
rm -f $ca_key $leaf_key $csr $ext
print $"✅ Cert: ($cert) — commit this"
print $"✅ Key encrypted: ($secret)"
print $"Wire it up: age.secrets.($slug)-tls-key.file = ../($secret);"
}
# Update one or all packages. With a version, bumps explicitly.
# Without a version, auto-detects the latest from upstream.
#
# skyg pkgs update --all
# skyg pkgs update buzz-desktop
# skyg pkgs update buzz-desktop 0.6.0
export def "skyg pkgs update" [
pkg_name?: string@updatable-pkgs # Package to update (omit with --all)
version?: string # Explicit version (omit for auto-detect)
--all # Update all packages that have update.sh
] {
cd $REPO_ROOT
if $all and $version != null {
error make {msg: "Cannot use --all with a specific version. Run without --all to bump a single package."}
}
let targets = if $all {
updatable-pkgs
} else if $pkg_name != null {
[$pkg_name]
} else {
error make {msg: "Specify a package name or use --all to update all packages"}
}
if ($targets | length) == 0 {
print "No updatable packages found (no pkgs/*/update.sh scripts)"
return
}
print $"Updating ($targets | length) package\(s): ($targets | str join ', ')"
print ""
for pkg in $targets {
let update_script = $"pkgs/($pkg)/update.sh"
if not ($update_script | path exists) {
print $"⚠️ Skipping ($pkg) — no update.sh"
continue
}
print $"=== ($pkg) ==="
cd $"pkgs/($pkg)"
try {
if $version != null {
bash $"update.sh ($version)" | print
} else {
bash "update.sh" | print
}
} catch { |e|
print $"❌ Failed to update ($pkg): ($e)"
}
cd $REPO_ROOT
print ""
}
print ""
if $version != null {
print "Bump complete. Review with:"
git --no-pager diff pkgs/ | print
} else {
print "All updates complete. Review with:"
git --no-pager diff pkgs/ | print
}
}