86 lines
2.2 KiB
Bash
Executable File
86 lines
2.2 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# switch-system: rebuild and activate this machine from the flake.
|
|
# Uses `nh os` when available, else `sudo nixos-rebuild`.
|
|
set -euo pipefail
|
|
|
|
HOST=
|
|
FLAKE_ARG=
|
|
ACTION=switch
|
|
|
|
die() {
|
|
printf 'error: %s\n' "$*" >&2
|
|
exit 1
|
|
}
|
|
|
|
usage() {
|
|
cat <<'EOF'
|
|
Usage: switch-system [--host NAME] [--flake DIR] [boot|switch|test]
|
|
|
|
--host NAME flake host (default: this machine's host name)
|
|
--flake DIR flake directory (default: the repository you are in, else
|
|
~/nixos-config)
|
|
switch build, activate now and make it the boot default (default)
|
|
boot build and activate on next boot
|
|
test build and activate now without touching the boot entry
|
|
EOF
|
|
}
|
|
|
|
while [ "$#" -gt 0 ]; do
|
|
case "$1" in
|
|
--host)
|
|
[ "$#" -ge 2 ] || die "--host needs a value"
|
|
HOST=$2
|
|
shift 2
|
|
;;
|
|
--flake)
|
|
[ "$#" -ge 2 ] || die "--flake needs a value"
|
|
FLAKE_ARG=$2
|
|
shift 2
|
|
;;
|
|
boot | switch | test)
|
|
ACTION=$1
|
|
shift
|
|
;;
|
|
-h | --help)
|
|
usage
|
|
exit 0
|
|
;;
|
|
*) die "unknown argument: $1 (see --help)" ;;
|
|
esac
|
|
done
|
|
|
|
if [ -z "$HOST" ]; then
|
|
HOST=$(cat /proc/sys/kernel/hostname)
|
|
fi
|
|
|
|
# After `sudo`, $HOME can be root's: prefer the home of the invoking user.
|
|
home=$HOME
|
|
if [ -n "${SUDO_USER:-}" ]; then
|
|
home=$(getent passwd "$SUDO_USER" | cut -d: -f6)
|
|
fi
|
|
|
|
if [ -n "$FLAKE_ARG" ]; then
|
|
DIR=$FLAKE_ARG
|
|
elif top=$(git rev-parse --show-toplevel 2>/dev/null) && [ -f "$top/flake.nix" ]; then
|
|
DIR=$top
|
|
elif [ -f "$home/nixos-config/flake.nix" ]; then
|
|
DIR=$home/nixos-config
|
|
else
|
|
die "no flake found: run inside the repository or pass --flake DIR"
|
|
fi
|
|
[ -f "$DIR/flake.nix" ] || die "no flake.nix in $DIR"
|
|
DIR=$(readlink -f "$DIR")
|
|
|
|
# Flakes only see files tracked by git: warn about new, untracked files.
|
|
if git -C "$DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
|
untracked=$(git -C "$DIR" ls-files --others --exclude-standard)
|
|
if [ -n "$untracked" ]; then
|
|
printf 'warning: untracked files are invisible to the flake (git add them):\n%s\n' "$untracked" >&2
|
|
fi
|
|
fi
|
|
|
|
if command -v nh >/dev/null 2>&1; then
|
|
exec nh os "$ACTION" --hostname "$HOST" "$DIR"
|
|
fi
|
|
exec sudo nixos-rebuild "$ACTION" --flake "$DIR#$HOST"
|