#!/bin/sh

if git rev-parse --verify HEAD >/dev/null 2>&1
then
	against=HEAD
else
	# Initial commit: diff against an empty tree object
	against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

OLD_IFS="$IFS"

IFS='
'
ERROR=0

for FILE_LINE in $( git diff-index --check --cached ${against} | sed '/^[+-]/d' )
do
	#preparation
	COLON_COUNT=$( printf "${FILE_LINE}" | grep -o ":" | wc -l ) #catch files with colons in their names, like: "a:b.cc"
	FILE=$( printf "${FILE_LINE}" | cut -f1-$(($COLON_COUNT - 1)) -d":" )
	FILE_BASENAME=$( basename "${FILE}" )
	FILE_DIRNAME=$( dirname "${FILE}" )
	LINE=$( printf "${FILE_LINE}" | cut -f$COLON_COUNT -d":" )
	#echo $FILE_LINE

	#do the work
	OBJECT_HASH=$( git show ":${FILE}" | sed "${LINE}s/[[:space:]][[:space:]]*$//" | git hash-object --stdin -w ) # add ;:a ${LINE}s/([ ]+)([\t]+)/\2\1/g;ta and -r to sed command to "fix" space before tab. Most likely this kills your identation.
	FILE_MODE=$( git ls-files -c --stage "${FILE_DIRNAME}" | grep "${FILE_BASENAME}" | cut -f1 -d" " )
	#echo "${FILE_MODE}" "${OBJECT_HASH}" "${FILE}"
	git update-index --cacheinfo "${FILE_MODE}" "${OBJECT_HASH}" "${FILE}"
	if [ $? -ne 0 ]; then
		echo "${FILE}:${LINE}: Could not fix possible trailing space errors. The index may be tainted. Call 'git diff \"${FILE}\"' to compare the index to the working directory."
		ERROR=1
	fi
done

IFS="$OLD_IFS"

case $ERROR in
0)
	#there was no error
	exit 0
	;;
*)
	#there was an error
	echo "Aborted: The index may be tainted. Bypass attempts for automatic whitespace error fixing with the --no-verify option to git-commit."
	exit 1
	;;
esac