#!/nix/store/gik3rh1vz2jlgnifb9dh6vc6sxwwz9jj-bash-5.3p9/bin/bash
set -o errexit
set -o nounset
set -o pipefail

export PATH="$PATH"

# pre-switch check switchInhibitors
if ! (
  incoming="${1-}"
action="${2-}"

case "$action" in
  boot|dry-activate)
    echo "Not checking switch inhibitors (action = $action)"
    exit
    ;;
esac

echo -n "Checking switch inhibitors..."

current_inhibitors="/run/current-system/switch-inhibitors"
if [ ! -f "$current_inhibitors" ]; then
  current_inhibitors="/nix/store/dkff9gbfc0fba250kh1ws327krh4s2js-empty-inhibitors"
fi

new_inhibitors="$incoming/switch-inhibitors"
if [ ! -f "$new_inhibitors" ]; then
  new_inhibitors="/nix/store/dkff9gbfc0fba250kh1ws327krh4s2js-empty-inhibitors"
fi

diff="$(
  /nix/store/s04d6wm3kqjdgr7zdhlk214f6a2291ks-jq-1.8.1-bin/bin/jq \
    --raw-output \
    --null-input \
    --rawfile current "$current_inhibitors" \
    --rawfile newgen "$new_inhibitors" \
  '
    ($current | fromjson) as $old |
    ($newgen | fromjson) as $new |
    $old |
    to_entries |
    map(
      select(.key | in ($new)) |
      select(.value != $new.[.key]) |
      [ .key, ":", .value, "->", $new.[.key] ] | join(" ")
    ) |
    join("\n")
  ' \
)"

if [ -n "$diff" ]; then
  echo
  echo "There are changes to critical components of the system:"
  echo
  echo "$diff"
  echo
  echo "Switching into this system is not recommended."
  echo "You probably want to run 'nixos-rebuild boot' and reboot your system instead."
  echo
  echo "If you really want to switch into this configuration directly, then"
  echo "you can set NIXOS_NO_CHECK=1 to ignore pre-switch checks."
  echo
  echo "WARNING: doing so might cause the switch to fail or your system to become unstable."
  echo
  exit 1
else
  echo " done"
fi

) >&2 ; then
  echo "Pre-switch check 'switchInhibitors' failed" >&2
  exit 1
fi


