#!/bin/bash

indent() {
	sed 's/^/       /'
}

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

ASTYLE_PARAMETERS="-p -H -f -j -z2 -c -k3 -U -A8"
FILE_PATTERN="^(src|test)/.*\.(c|cpp|h)$"

echo "-----> Checking code with astyle"
for file in `git diff-index --cached --name-only HEAD --diff-filter=ACMR |  egrep $FILE_PATTERN`; do
	# nf is the temporary checkout. This makes sure we check against the
	# revision in the index (and not the checked out version).
	temp_checkout=`git checkout-index --temp ${file} | cut -f 1`
	formatted=`mktemp /tmp/${temp_checkout}.formatted` || exit 1
	diff=`mktemp /tmp/${temp_checkout}.diff` || exit 1
	astyle ${ASTYLE_PARAMETERS} < $temp_checkout > $formatted 2>/dev/null
	failed=$?
	diff -u -p "${temp_checkout}" "${formatted}" > ${diff}
	different=$?
	if [ $failed != 0 ]; then
		echo "       `astyle` failed on: $file"
		echo "       Please investigate this situation. You'll want:"
		echo
		echo "       astyle ${ASTYLE_PARAMETERS} $file"
	elif [ $different != 0 ]; then
		echo "       Code style error in: $file"
		cat "${diff}" | indent | indent
		echo
		echo "       If the whole file is to be committed, you can format and re-stage it with:"
		echo
		echo "       astyle ${ASTYLE_PARAMETERS} -n $file; git add $file"
		rm "${temp_checkout}" "${formatted}" "${diff}"
		exit 1
	else
		rm "${temp_checkout}" "${formatted}" "${diff}"
	fi
done
echo "       astyle passed"

