#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by git-commit with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, make this file executable.

# This is slightly modified from Andrew Morton's Perfect Patch.
# Lines you introduce should not have trailing whitespace.
# Also check for an indentation that has SP before a TAB.

output_failing_line() {
	while [ $# -gt 0 ]; do
		lineno=${1/:*/}
		lineno=$((${lineno}-5))
		line=${1/*+/}
		echo "${lineno} : ${line}"
		shift
	done
}

if git-rev-parse --verify HEAD 2>/dev/null
then
	OLDIFS=${IFS}
	IFS=$'\n'
	error=0
	FILE_LIST=$(git-diff-index --name-only  -M --cached  HEAD --)
	for file in ${FILE_LIST}; do
		line_count=$(wc -l ${file})
		line_count=${line_count/ */}
		trailing=$(git-diff -p --unified=${line_count} --cached HEAD -- ${file} | grep -En '^\+.*[[:blank:]]+[[:space:]]$')
		badindent=$(git-diff -p --unified=${line_count} --cached HEAD -- ${file} | grep -En '^\+[ ]*	')
		badline=$(git-diff -p --unified=${line_count} --cached HEAD -- ${file} | grep -En '^\+(?:[<>=]){7}')
		if [ -n "${trailing}" ] || [ -n "${badindent}" ] || [ -n "${badline}" ]; then
			echo
			echo "------ FAILED PRE COMMIT CHECK -----"
			echo You have some suspicious patch lines:
			echo ${file} : trailing whitespace
			output_failing_line ${trailing}
			echo ${file} : indent SP followed by a TAB
			output_failing_line ${badindent}
			echo ${file} : unresolved merge conflict
			output_failing_line ${badline}
			echo "------ FAILED PRE COMMIT CHECK -----"
			error=1
		fi
	done
   exit ${error}
else
	# NEEDSWORK: we should produce a diff with an empty tree here
	# if we want to do the same verification for the initial import.
	:
fi

