bij/bij.sh
2024-04-07 15:32:30 +02:00

87 lines
1.3 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
FLAKE=
TARGET=
ARGS=()
OPTS=()
while [[ $# -gt 0 ]]; do
case $1 in
--flake)
FLAKE="$2"
shift
shift
;;
--target)
TARGET="$2"
shift
shift
;;
--)
shift
OPTS=( "$@" )
break
;;
-*)
echo "unknown option: $1"
exit 1
;;
*)
ARGS+=("$1")
shift
;;
esac
done
set -- "${ARGS[@]}"
if [[ -z ${FLAKE} ]]; then
# Flake not specified, use working directory
FLAKE="$(pwd)"
fi
if [[ "${#ARGS[@]}" -lt 1 ]]; then
echo "Command not specified"
exit 1
fi
COMMAND="${ARGS[0]}"
if [[ "${COMMAND}" != "apply" && "${COMMAND}" != "build" && "${COMMAND}" != "exec" ]]; then
echo "Unsupported command: ${COMMAND}"
exit 1
fi
if [[ "${#ARGS[1]}" -lt 2 ]]; then
echo "Host not specified"
exit 1
fi
HOST="${ARGS[1]}"
if [[ -z ${TARGET} ]]; then
# Use fqdn as target
TARGET="$(nix --extra-experimental-features "nix-command flakes" eval --raw "${FLAKE}#nixosConfigurations.${HOST}" --apply "host: host.config.networking.fqdn")"
fi
case "${COMMAND}" in
apply)
nixos-rebuild switch --flake "${FLAKE}#${HOST}" --target-host "${TARGET}" --use-substitutes --use-remote-sudo
;;
build)
nixos-rebuild build --flake "${FLAKE}#${HOST}"
;;
exec)
# shellcheck disable=SC2029
ssh -t "${TARGET}" "${OPTS[@]}"
;;
*)
echo "Unsupported command: ${COMMAND}"
exit 1
;;
esac