#!/bin/bash

[ -e /etc/init.d/functions.sh ] && source /etc/init.d/functions.sh

ret=0

testit() {
	if [ -s $1 ] ; then
		echo ${BAD}FAIL${NORMAL}: $1
		cat $1
		rm -f $1
		ret=1
		return
	fi
	rm -f $1
	echo ${GOOD}PASS${NORMAL}: $1
}


#
# check for misc common typos
#
find ../.. \
	'(' -type d -a '(' -name CVS -o -name tests ')' -prune ')' \
	-o '(' -type f -a -print0 ')' | xargs -0 \
	grep -n -I \
		-e '\<compatability\>' \
		-e '\<compatable\>' \
		-e '\<fordeground\>' \
		-e '\<depency\>' \
		-e '\<defalt\>' \
		-e '\<remaing\>' \
		-e '\<queuing\>' \
		-e '\<detatch\>' \
		-e '\<sempahore\>' \
		-e '\<reprenstative\>' \
		-e '\<overriden\>' \
		-e '\<readed\>' \
		-e '\<formated\>' \
		-e '\<algorithic\>' \
		-e '\<deamon\>' \
		-e '\<derefernce\>' \
		-e '\<lenght\>' \
		| sed -e "s:^\.\./\.\./::g" > src.typos
testit src.typos



#
# don't allow obsolete functions
#
find ../.. '(' -name '*.c' -o -name '*.h' ')' -print0 | xargs -0 \
	grep -n -E -e '\<(bcmp|bcopy|bzero|getwd|index|mktemp|rindex|utimes)\>[[:space:]]*\(' \
	| sed -e "s:^\.\./\.\./::g" > src.obsolete.funcs
testit src.obsolete.funcs



#
# make sure people use our constants
#
find ../.. '(' -name '*.c' -o -name '*.h' ')' -print0 | xargs -0 \
	grep -n -E -e '\<PATH_MAX\>' | grep -v __PAX_UTILS_PATH_MAX \
	| sed -e "s:^\.\./\.\./::g" > src.bad.constants
testit src.bad.constants



#
# don't allow obsolete headers
#
find ../.. '(' -name '*.c' -o -name '*.h' ')' -print0 | xargs -0 \
	grep -n -E -e '\<(malloc|memory|sys/(errno|fcntl|signal|stropts|termios|unistd))\.h\>' \
	| sed -e "s:^\.\./\.\./::g" > src.obsolete.headers
testit src.obsolete.headers



#
# make sure people use the x* helper funcs
#
xfuncs=$(printf '%s|' $(sed -n 's:.*x\([^(]*\)(.*:\1:p' ../../xfuncs.h))
xfuncs=${xfuncs:0:${#xfuncs}-1}
find ../.. '(' -name '*.c' -o -name '*.h' ')' -print0 | xargs -0 \
	grep -n -E -e "\<(${xfuncs})[[:space:]]*\(" \
	| grep -v xfuncs.c \
	| sed -e "s:^\.\./\.\./::g" > src.use.xfuncs
testit src.use.xfuncs


#
# check for style
#
find ../.. '(' -name '*.c' -o -name '*.h' ')' -print0 | xargs -0 \
	grep -n -E \
		-e '\<(for|if|switch|while)\(' \
		-e '\<(for|if|switch|while) \( ' \
		-e ' ;' \
		-e '[[:space:]]$' \
		-e '\){' \
		-e '(^|[^:])//' \
	| sed -e "s:^\.\./\.\./::g" > src.style
testit src.style


# Stupid BSD makes us check for this..
if [ $(type -P md5sum) != "" ]; then
	for x in $(find ../.. '(' -name '*.c' -o -name '*.h' ')' ); do
		python space.py $x > $x~
		if [[ $(md5sum $x | awk '{print $1}') != $(md5sum $x~ | awk '{print $1}') ]]; then
			diff -u $x $x~
			#cp $x~ $x
		fi
		rm $x~
	done > src.space
	testit src.space
fi

exit ${ret}
