#!/bin/sh

filter=$(git config hooks.filter)
validation=$(git config hooks.validation)
indentation=$(git config hooks.indentation)
temp=$(mktemp -p /dev/shm -d -t git-hook.XXXX)
export GIT_DIR=$(git rev-parse --show-toplevel)/.git

new() {
	git status --porcelain | grep -E '^AM|^M|^A' | sed 's/^[^ ]* *//'
}

check() {
	file=$2
	luajit -e "
	for line in assert(io.open('$file')):lines() do
		if not line:match('^%s*'):match('^$1*$') then
			print('File \x1b[31m$file\x1b[00m is incorrectly indented!')
			os.exit(1)
		end
	end"
}

git checkout-index --prefix="$temp/index/" --all

cd $temp/index/

if [ -n "$filter" ]; then
	ln -s $GIT_DIR/ .git
	$filter
	git add --all
	rm -rf .git
fi

if [ -n "$validation" ]; then
	$validation || error=1
fi

case $indentation in
	tab|tabs)
		echo "Checking tab indentation"
		for file in $(new); do
			check '\t' $file || error=1
		done
		;;
	space|spaces)
		echo "Checking space indentation"
		for file in $(new); do
			check ' ' $file || error=1
		done
		;;
	""|off)
		echo "Skipping indentation check"
		;;
	*)
		echo "Cannot check for indentation type \033[31m'$indentation'\033[00m"
		exit 1
		;;
esac

cd $GIT_DIR
rm -rf $temp

if [ -z "$error" ]
then exit 0
else exit 1
fi

hook=$(basename $0)
if [ -f $GIT_DIR/hooks/$hook ]
then
	echo Running project-level hook: $GIT_DIR/hooks/$hook
	$GIT_DIR/hooks/$hook
fi