#!/bin/bash
#
# Check that the code follows a consistant code style
#

FORMATER=clang-format

# Check for existence of clang-format, and error out if not present.
if [ ! -x "$(which $FORMATER)" ]; then
	echo "git pre-commit hook:"
	echo "Did not find clang-format, please install it before continuing."
	exit 1
fi

FILE_PATTERN="\.(c|cpp|h)$"
IGNORE_PATTERN="^src/lib/"

echo "--Checking style--"
for file in `git diff-index --cached --name-only HEAD --diff-filter=ACMR| egrep $FILE_PATTERN| egrep -v $IGNORE_PATTERN` ; do
	# nf is the temporary checkout. This makes sure we check against the
	# revision in the index (and not the checked out version).
	nf=`git checkout-index --temp ${file} | cut -f 1`
	newfile=`mktemp /tmp/${nf}.XXXXXX` || exit 1
	clang-format< $nf > $newfile 2>> /dev/null
	diff -u -p "${nf}" "${newfile}"
	r=$?
	rm "${newfile}"
	rm "${nf}"
	if [ $r != 0 ] ; then
		echo "================================================================================================="
		echo " Code style error in: $file "
		echo " "
		echo " Please fix before committing. Don't forget to run git add before trying to commit again. "
		echo " If the whole file is to be committed, this should work (run from the top-level directory): "
		echo " "
		echo " $FORMATER $file; git add $file; git commit"
		echo " "
		echo "================================================================================================="
	exit 1
	fi
done
echo "--Checking style pass--"

