#!/bin/sh

[ $(which astyle) ] || exit 1

function astyle_commit ()
{
    break=0;
    echo "astyle'ing commited files..."
    # only astyle what has changed 
    for i in $(git diff-index --name-only HEAD)
    do
	# only astyle what is a sourcefile
	if grep -q "\(\.cpp\|\.h\)$" <<< $i; then
	    if [ -n "$(astyle --options=$(pwd)/astylerc | grep -q "formatted")" ]; then
                break=1;
            fi
	fi
    done
    if [ $break -eq 1 ]; then
        echo "Some files were modified by astyle, please update your commit."
        exit 1
    fi
    echo "done"
}

if test -d $(pwd)/.git ; then  # daddy are we there yet?
    astyle_commit 
else  # soon love
    cd $(git rev-parse --git-dir | sed s/\.git//)
    astyle_commit 
fi
find -name '*.orig' -delete
