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

# Redirect output to stderr.
exec 1>&2

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

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

# http://man.openbsd.org/sed#r
# http://man.openbsd.org/sed#E
# http://netbsd.gw.com/cgi-bin/man-cgi?sed++NetBSD-current
# https://github.com/freebsd/freebsd/blob/master/usr.bin/sed/main.c
# http://git.savannah.gnu.org/gitweb/?p=sed.git;a=blob;f=sed/sed.c
# GNU has -r and -E (undocumented); MacOS has -E but not -r; Sunos has neither.
files=$(git diff-index --name-status --cached HEAD | grep -v ^D | sed -E "s/^[A-Z]+[A-Z0-9]*[ \t]+/ /")

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

#-------------------------------------------------------------------------------
# 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 -i copyright | grep -c -i $user` -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

exit 0
