# 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.
# Drawback: it will query info about missing paths twice
# 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"

info "Figuring current specialisation"
systemLink=
currentSystem="$(readlink -f /run/current-system)"
while read -r system
do
    if [ "$(readlink -f "$system")" = "$currentSystem" ]
    then
        systemLink="$system"
        break
    fi
done <<< "$(ls -d /nix/var/nix/profiles/system-*-link{,/specialisation/*})"

specialisationArgs=()
if [ -n "$systemLink" ]
then
    specialisation=$(echo "$systemLink" | cut -d/ -f8)
    if [ -n "$specialisation" ]
    then
        specialisationArgs=("--specialisation" "$specialisation")
    fi
else
    warn "Could not find link for $currentSystem, will switch to non-specialized system"
fi



# Apply
confirm="n"
if [ "$verb" = "confirm" ]
then
  warn "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
  warn "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