summary refs log tree commit diff
path: root/scripts/nx.sh
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/nx.sh')
-rwxr-xr-xscripts/nx.sh148
1 files changed, 148 insertions, 0 deletions
diff --git a/scripts/nx.sh b/scripts/nx.sh
new file mode 100755
index 0000000..245531c
--- /dev/null
+++ b/scripts/nx.sh
@@ -0,0 +1,148 @@
+#!/usr/bin/env bash
+
+# a small useful script for quickly accessing different nix and nixos commands
+# through a single nice interface.
+# run `nx help` for command list!
+
+set -euo pipefail
+
+config="/etc/configuration"
+current_hostname="$(hostname)"
+
+run() {
+	echo -ne "* \033[1;33m"
+	echo "$@"
+	echo -ne "\033[0m"
+	$@
+}
+
+error() {
+	echo -ne "\033[1;31m"
+	echo -n "error: "
+	echo -ne "\033[0m"
+	echo "$@"
+}
+
+rebuild() {
+	local target="$1"
+	local tool="$2"
+
+	run nixos-rebuild --sudo --builders "\"\"" --flake "$config#$target" "$tool"
+}
+
+flag() {
+	local f="$1"
+
+	case "$f" in
+	-h | --here)
+		config="."
+		;;
+	*)
+		error "unknown flag '$f'"
+		exit 1
+		;;
+	esac
+}
+
+apply_command() {
+	rebuild "$current_hostname" "switch"
+}
+
+apply_boot_command() {
+	rebuild "$current_hostname" "boot"
+}
+
+test_command() {
+	local given_host="${1:-}"
+
+	local target
+
+	if [ -z "$given_host" ]; then
+		target="$current_hostname"
+	else
+		target="$given_host"
+	fi
+
+	run nix build "$config#nixosConfigurations.$target.config.system.build.toplevel" --dry-run
+}
+
+repl_command() {
+	local given_host="${1:-}"
+
+	local target
+
+	if [ -z "$given_host" ]; then
+		target="$current_hostname"
+	else
+		target="$given_host"
+	fi
+
+	rebuild "$target" "repl"
+}
+
+garbage_command() {
+	local given_period="${1:-}"
+
+	if [ -z "$given_period" ]; then
+		run sudo nix-collect-garbage -d
+	else
+		run sudo nix-collect-garbage --delete-older-than "$given_period"
+	fi
+}
+
+help_command() {
+	echo "usage: nx <command> [args] [flags]"
+	echo ""
+	echo "commands:"
+	echo "  apply         apply nixos configuration and switch to it"
+	echo "  apply-boot    apply nixos configuration on next boot"
+	echo "  test [host]   try building configuration of a host (default: current host)"
+	echo "  repl [host]   start repl with host configuration (default: current host)"
+	echo "  garbage [age] collect garbage (default: all)"
+	echo ""
+	echo "flags:"
+	echo "  --here, -h    evaluate configuration in current directory"
+}
+
+args=()
+for arg in "$@"; do
+	if [[ "$arg" == -* ]]; then
+		flag "$arg"
+	else
+		args+=("$arg")
+	fi
+done
+
+command="${args[0]:-}"
+
+if [ -z "$command" ]; then
+	error "no command given!"
+	echo ""
+	help_command
+	exit 1
+fi
+
+case "$command" in
+help)
+	help_command
+	;;
+apply)
+	apply_command
+	;;
+apply-boot)
+	apply_boot_command
+	;;
+test)
+	test_command "${args[1]:-}"
+	;;
+repl)
+	repl_command "${args[1]:-}"
+	;;
+garbage)
+	garbage_command "${args[1]:-}"
+	;;
+*)
+	error "unknown command '$command'"
+	exit 1
+	;;
+esac