#!/bin/bash

# This script can be symlinked as a pre-commit hook in a git repo.
# Additionally, it also supports passing in filenames as cmdline parameters, like e.g. pycodestyle does.

new=$(mktemp)
function finish
{
	rm -rf "$new"
}
trap finish EXIT

fix=
if [ "$1" == "--fix" ]; then
	fix=1
	shift
fi

files="$@"
if [ -z "$files" ]; then
	# gtktpconv uses clang-format
	files="$(git diff --name-only --cached|grep -v gtktpconv)"
fi
for file in $files
do
	if ! echo $file |grep -q '\(cxx\|cpp\|hxx\)$'; then
		continue
	fi
	if [ ! -e "$file" ]; then
		continue
	fi

	options=""
	i="$PWD/$(dirname $file)"
	while true
	do
		if [ -e "$i/astyle.options" ]; then
			options="$i/astyle.options"
			break
		elif [ "$i" == "" ]; then
			break
		fi
		i=${i%/*}
	done
	if [ -z "$options" ]; then
		options=$HOME/.astyle.options
	fi

	astyle --options=$options < $file > $new
	if ! diff -u $file $new; then
		if [ -n "$fix" ]; then
			cat $new > $file
			echo "Fixed the above errors."
		else
			echo "You had some style errors."
		fi
		exit 1
	fi
done
