#!/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

files=$(git diff-index --name-status --cached HEAD | grep -v ^D | sed -r "s/^[A-Z]+[A-Z0-9]*[ \t]+/ /")

# Redirect output to stderr.
exec 1>&2

#-------------------------------------------------------------------------------
# Check the copyright notice of all files to be commited.

user=`git config --global user.email`
year=`date +"%Y"`

missing_copyright_year=""
if test $user = "erikd@mega-nerd.com" ; then
	for f in $files ; do
		if test `head -5 $f | grep -c -i copyright` -gt 0 ; then
			user_copyright=`grep -i copyright $f | grep $user | grep -c $year`
			if test $user_copyright -lt 1 ; then
				missing_copyright_year="$missing_copyright_year $f"
				fi
			fi
		done
	fi

if test -n "$missing_copyright_year" ; then
	echo "Missing current year in the copyright notice of the following files:"
	for f in $missing_copyright_year ; do
		echo "    $f"
		done
	echo "Commit aborted."
	exit 1
	fi

#-------------------------------------------------------------------------------
# Check the formatting of all C files.

cfiles=""
for f in $files ; do
	if test `dirname $f` = "src/ALAC" ; then
		echo "Skipping cstyle checking on $f"
	elif test `echo $f | grep -c "\.[ch]$"` -gt 0 ; then
		cfiles="$cfiles $f"
		fi
	done

if test -n "$cfiles" ; then
	Scripts/cstyle.py $cfiles
	if test $? -ne 0 ; then
		echo
		echo "Commit aborted. Fix the above error before trying again."
		exit 1
		fi
	fi

#-------------------------------------------------------------------------------
# Prevent files with non-ascii filenames from being committed.

if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 ; then
	echo "Error: Attempt to add a non-ascii file name."
	echo
	echo "This can cause problems if you want to work"
	echo "with people on other platforms."
	echo
	echo "To be portable it is advisable to rename the file ..."
	echo
	echo "Commit aborted."
	exit 1
	fi

exit 0