#!/nix/store/lw117lsr8d585xs63kx5k233impyrq7q-bash-5.3p3/bin/bash
set -o errexit
set -o nounset
set -o pipefail

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

if [ "$action" == "boot" ]; then
  echo "Not checking switch inhibitors (action = $action)"
  exit
fi

echo -n "Checking switch inhibitors..."

# Create a temporary file that we use in case a generation does not have
# the switch-inhibitors file.
empty="$(/nix/store/d75200gb22v7p0703h5jrkgg8bqydk5q-coreutils-9.8/bin/mktemp -t switch_inhibit.XXXX)"
# shellcheck disable=SC2329
clean_up() {
  /nix/store/d75200gb22v7p0703h5jrkgg8bqydk5q-coreutils-9.8/bin/rm -f "$empty"
}
trap clean_up EXIT
echo "{}" > "$empty"

current_inhibitors="$(/nix/store/d75200gb22v7p0703h5jrkgg8bqydk5q-coreutils-9.8/bin/realpath /run/current-system)/switch-inhibitors"
if [ ! -f "$current_inhibitors" ]; then
  current_inhibitors="$empty"
fi

new_inhibitors="$(/nix/store/d75200gb22v7p0703h5jrkgg8bqydk5q-coreutils-9.8/bin/realpath "$incoming")/switch-inhibitors"
if [ ! -f "$new_inhibitors" ]; then
  new_inhibitors="$empty"
fi

diff="$(
  /nix/store/zssasryipb2x4gk2ahzacl4mvvcmk48j-jq-1.8.1-bin/bin/jq \
    --raw-output \
    --null-input \
    --rawfile current "$current_inhibitors" \
    --rawfile newgen "$new_inhibitors" \
  '
    $current | try fromjson catch {} as $old |
    $newgen | try fromjson catch {} 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


