#!/bin/sh

# use as .git/hooks/pre-commit

exec 1>&2

RET=0
changed=$(git diff --cached --name-only)
crustified=""
tomesonfmt=""

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
  if echo $f | grep \meson\.build\$ > /dev/null
  then
    meson fmt -q $f
    if test $? = 1 ;
    then
      tomesonfmt=" $tomesonfmt $f"
      RET=1
    fi
  fi
done

if [ $RET = 1 ];
then
  echo "================================================================"
  echo " Format your code!                                              "
  echo " See https://docs.gnunet.org/latest/developers/style.html#coding-style "
  echo "================================================================"
  echo "Run:"
  if [ -n "$crustified" ];
  then
    echo "$ uncrustify --replace --no-backup -c uncrustify.cfg ${crustified}"
  fi
  if [ -n "$tomesonfmt" ];
  then
    echo "$ meson fmt -i ${tomesonfmt}"
  fi
  echo "Do not forget to readd and commit afterwards!"
  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

# Do not fail
exit 0
