#!/usr/bin/env bash # Updates NixOS from a throwaway worktree of this repo, so the checkout you edit in # is left alone until the update is done. Started from the "Desktop" half of the # control centre's update tile in a kitty window (installed as `nixos-update`, # modules/home/packages.nix, which sets DOT_REPO). # # 1. a temporary worktree of main # 2. nix flake update, committed there # 3. nixos-rebuild build, then nvd's list of what changed against the running system # 4. asks before going on; then pushes the commit, installs it as the next boot # entry (nixos-rebuild boot), brings your checkout's main up to date and reboots # # If anything fails, the window stays open until you press Enter, and nothing is # rebooted. set -E repo=${DOT_REPO:-$HOME/git/dot} tmp="" step() { printf '\n\e[1;34m==> %s\e[0m\n' "$*"; } note() { printf '\e[1;33m%s\e[0m\n' "$*"; } wait_close() { read -rp "Press Enter to close. " _ || true; } die() { trap - ERR printf '\n\e[1;31m%s\e[0m\n' "$*" wait_close exit 1 } cleanup() { if [ -n "$tmp" ]; then git -C "$repo" worktree remove --force "$tmp" 2>/dev/null || true rm -rf "$tmp" tmp="" fi } trap 'die "The update failed (see above). Nothing was rebooted."' ERR trap cleanup EXIT step "Fetching $repo" git -C "$repo" worktree prune git -C "$repo" fetch origin main git -C "$repo" merge-base --is-ancestor origin/main main || die "main in $repo is behind origin/main (or has diverged); pull first." base=$(git -C "$repo" rev-parse main) ahead=$(git -C "$repo" rev-list --count origin/main..main) dirty=$(git -C "$repo" status --porcelain) tmp=$(mktemp -d -t dot-update.XXXXXX) step "Creating a worktree of main in $tmp" git -C "$repo" worktree add --detach "$tmp" main cd "$tmp" || die "Could not enter $tmp." step "Updating flake inputs" nix flake update --commit-lock-file if [ "$(git rev-parse HEAD)" = "$base" ]; then printf '\nEverything is already up to date.\n' wait_close exit 0 fi step "Building" nixos-rebuild build --flake "$tmp" step "What changes" git --no-pager log -1 --format=%b nvd diff /run/current-system "$tmp/result" echo [ -z "$dirty" ] || note "Uncommitted changes in $repo are not part of this update." [ "$ahead" -eq 0 ] || note "main has $ahead commit(s) not on GitHub yet; they are pushed too." read -rp "Commit, push, install and reboot? [y/N] " answer || answer="" case $answer in [yY]*) ;; *) echo "Nothing was changed." sleep 1 exit 0 ;; esac step "Pushing" git push origin HEAD:main step "Installing as the next boot entry" nixos-rebuild boot --sudo --flake "$tmp" step "Updating main in $repo" commit=$(git rev-parse HEAD) if [ "$(git -C "$repo" symbolic-ref --quiet --short HEAD)" = main ]; then git -C "$repo" merge --ff-only "$commit" else git -C "$repo" update-ref refs/heads/main "$commit" "$base" fi cd "$repo" cleanup trap 'printf "\nReboot cancelled. The update boots next time.\n"; wait_close; exit 0' INT step "Rebooting in 5 seconds (Ctrl+C to cancel)" sleep 5 systemctl reboot