dotfiles/os/rebuild.sh
2025-01-23 18:46:13 +01:00

79 lines
2.2 KiB
Bash

# Handle arguments
self="$1"
verb="$2"
shift
shift
# Helpers
error() {
echo -e '\033[1;31m'"$*"'\033[0m'
}
warn() {
echo -e '\033[1;33m'"$*"'\033[0m'
}
info() {
echo -e '\033[1;34m'"$*"'\033[0m'
}
debug() {
[ ! -v DEBUG ] || echo -e '\033[1;35m'"$*"'\033[0m'
}
if [ "$verb" != "build" ] && [ "$verb" != "test" ] && [ "$verb" != "boot" ] && [ "$verb" != "switch" ] && [ "$verb" != "confirm" ]
then
error "Action should be one of: build, test, boot, switch, confirm"
exit 2
fi
info "Evaluating"
# Evaluating can take a lot of memory, and Nix doesn't free it until the program ends,
# which can be limiting on memory-constrained devices. Hence the build step is separate.
# nix eval doesn't use the eval cache, so we do a nix build --dry-run
# sudo so the eval cache is shared with nixos-rebuild
json=$(time sudo nix build "$self#nixosConfigurations.$HOSTNAME.config.system.build.toplevel" --dry-run --json )
toplevel=$(echo "$json" | jq '.[0].outputs.out' -r)
derivation=$(echo "$json" | jq '.[0].drvPath' -r)
info "Building"
sudo nom build "$derivation^*" --no-link "$@"
info "Showing diff"
nvd diff "$(readlink -f /nix/var/nix/profiles/system)" "$toplevel"
# Figure out specialisation
specialisationArgs=()
currentSystem="$(readlink -f /run/current-system)"
while read -r specialisation
do
if [ "$(readlink -f "/nix/var/nix/profiles/system/specialisation/$specialisation")" = "$currentSystem" ]
then
debug "Using specialisation: $specialisation"
specialisationArgs=("--specialisation" "$specialisation")
fi
done <<< "$(ls /nix/var/nix/profiles/system/specialisation)"
# Apply
confirm="n"
if [ "$verb" = "confirm" ]
then
warning "Apply configuration? [y/N]"
read -r confirm
fi
if [ "$verb" = "test" ] || [ "$verb" = "switch" ] || [ "$confirm" = "y" ]
then
info "Applying"
"$toplevel/bin/update-password-store"
sudo nixos-rebuild --flake "$self#$HOSTNAME" test "${specialisationArgs[@]}" "$@"
fi
# Set as boot
if [ "$verb" = "confirm" ]
then
warning "Set configuration as boot? [y/N]"
read -r confirm
fi
if [ "$verb" = "boot" ] || [ "$verb" = "switch" ] || [ "$confirm" = "y" ]
then
info "Setting as boot"
sudo nixos-rebuild --flake "$self#$HOSTNAME" boot "$@"
fi