#!/usr/bin/env bash

# use as .git/hooks/pre-commit
exec 1>&2

RET=0
changed=$(git diff --cached --name-only | grep -v mustach)
crustified=""

# If nothing (important) has changed, return here
[ -z "$changed" ] && exit 0

( echo "$changed" | grep -q '\.[ch] *$*') && \
  echo "Checking formatting with uncrustify..."

for f in $changed;
do
 if echo $f | grep \\.[c,h]\$ > /dev/null
 then
    # compare result of uncrustify with changes
    #
    # only change any of the invocations here if
    # they are portable across all cmp and shell
    # implementations !
    uncrustify -q -c uncrustify.cfg -f $f | cmp -s $f -
    if test $? = 1 ;
    then
      crustified=" $crustified $f"
      RET=1
    fi
  fi
done

if [ $RET = 1 ];
then
  echo "Run"
  echo "uncrustify --replace -c uncrustify.cfg ${crustified}"
  echo "before committing."
  exit $RET
fi

# Make sure we have no stupid spelling error
if (which codespell > /dev/null)
then
    export REPORT=$(mktemp /tmp/codespellXXXXXX)
    ( set -o pipefail;
      echo "Checking for spelling errors with codespell...";
      contrib/ci/jobs/0-codespell/job.sh src 2> ${REPORT};
    ) || { echo "Please fix the code spell errors in ${REPORT} first"; exit 2; }
else
    echo "No codespell installed, skipping spell check."
    echo "** Please consider installing codespell! **"
fi


# Make sure doxygen is happy with our annotations
if (which doxygen > /dev/null) && [[ -e doc/doxygen/Makefile ]];
then
    export REPORT=$(mktemp /tmp/doxygenXXXXXX)
    [ -f doc/doxygen/Makefile ] && \
    ( set -o pipefail;
      echo "Checking that doxygen is happy..."
      cd doc/doxygen;
      make fast 2>&1 | tee ${REPORT} | (grep  error:; exit 0);
    ) || { echo "Please fix the errors reported by doxygen in ${REPORT} first"; exit 3; }
else
    echo "No doxygen installed, skipping check."
    echo "** Please consider installing doxygen! **"
fi

echo "Commit is all clear!"
