#!/bin/sh

# CVS client bogosec wrapper

# This wrapper will run bogosec on commited file which match the egrep regex
# seen below, and will exit with an eror code if the results do not meet the
# specified MAX_SCORE and MAX_SEV_POINTS defined below.  It is intended to
# run on the client side and can handle multiple simultaneously commited files.
# If the bogosec score beats the minimum requirements, the command line options
# passed to this script are echoed exactly to the actual cvs binary.

# Please call the script with the same options you would use when calling cvs!

# INSTALLATION
# * This script counts on the real cvs binary being in it's intended location
#	(meaning it can be found with a 'which cvs'.  Do not try and move it to a
#	different location and do something fancy with symlinks.
# * Simply add an alias to your ~/.bashrc file which looks something like this:
#		alias cvsb='/path/to/wrapper/client_cvs_wrapper'
# 	then run 'cvsb ACTION FILE' when you want to wrap the cvs client with
#	bogosec, and run 'cvs ACTION FILE' when you don't want any bogosec
#	interference.
#
# * Requires bogosec (plus any plugins) to be installed on the client

# CUSTOMIZATION
# This script runs bogosec on files which match the egrep regex seen below
# only when the cvs_command 'commit' is given.  If you would like to change
# this please edit COMMAND_HOOKS and replace it with a space delimited list
# of cvs commands you wish to wrap with bogosec.
#		Ex: COMMAND_HOOKS="log commit"

COMMAND_HOOKS="commit"

# you must adjust these to meet your needs
MAX_SCORE=0.10
MAX_SEV_PTS=999999

ORIG_ARGS=$*
RUN_BOGOSEC=0
TARGETS=""

PATH_TO_CVS=`which cvs`

while [ $# -gt 0 ]; do
	if [ `echo $1 | egrep -i '(\.c$|\.h$|\.cpp$|\.c\+\+$)'` ]; then
		TARGETS="$TARGETS $1"
	else
		for CMD in $COMMAND_HOOKS; do
			if [ "$1" = "$CMD" ]; then
				RUN_BOGOSEC=1
			fi
		done
	fi
	shift
done

if [ $RUN_BOGOSEC ]; then
	for FILE in $TARGETS; do
		echo "Running bogosec on $FILE"
		SCANNER_OUTPUT=`bogosec --plugin BogoFlaw --plugin BogoRats --plugin $FILE | tail -n 3`
		SEV_PTS=`echo $SCANNER_OUTPUT | awk -F" " '{print $2}'`
		SCORE=`echo $SCANNER_OUTPUT | awk -F"= " '{print $2}'`
		echo "bogosec score: $SCORE"
		echo "bogosec severity points: $SEV_PTS"
		SEV_RESULT=`echo "$SEV_PTS <= $MAX_SEV_PTS" | bc`
		SCORE_RESULT=`echo "$SCORE <= $MAX_SCORE" | bc`
		if [ $SCORE_RESULT -eq 0 ]; then
			echo "Your bogosec results did not beat maximum allowed score of $MAX_SCORE!"
			echo
			exit 1
		elif [ $SEV_RESULT -eq 0 ]; then
			echo "You bogosec results did not beat the maximum allowed severity points of $MAX_SEV_PTS!"
			echo
			exit 1
		fi
	done
fi
$PATH_TO_CVS $ORIG_ARGS
