#!/usr/bin/env bash
set -e

printf "%s\n" "Running nixfmt pre-commit hook.";
if ! which grep >/dev/null; then
  printf '%s\n' "ERR: grep not found.";
  exit 1;
fi;

ARCH="$(uname -m)-$(uname | tr "[:upper:]" "[:lower:]")"
NIX_FMT="$(nix build --no-link --print-out-paths .#formatter."${ARCH}")"

RESULT=0;
for file in $(git diff --name-only --cached); do
  if grep -q "\.nix$" <<< "${file}"; then
    "${NIX_FMT}"/bin/nixfmt -c <<< "$(git cat-file blob :"${file}")" 2> >(sed "s|<stdin>|${file}|");
    RESULT=$(( RESULT || $? ));
  fi;
done;

exit ${RESULT};