#! /bin/bash

# Run cc with "-###", harvest the corresponding commands and insert the
# code coverage filter.

if test "$CODECOV_FILE" == "" -o ! -s "$CODECOV_FILE"
then
        echo '$CODECOV_FILE is not set or is zero length.' 1>&2
        echo 'You need to edit a file and add a list of egrep patterns' 1>&2
        echo 'which describe what files you want code coverage on' 1>&2
        echo '(e.g. "src/sys/ifs/sfm/sfm.*\.c" or the like).' 1>&2
        echo 'After that, remember to "export CODECOV_FILE=<that file>".' 1>&2
        exit -1
fi

cmd=cc
wantcodecov_args=
nocodecov_args=
lastdash=false
skipnext=true
wantcodecov=
nocodecov=
skipcodecov=false
debug=unk

for i
do
        case "$i" in
        -O*)
                # Turn off optimization.
                lastdash=true
                skipnext=false
		nocodecov_args="$nocodecov_args $i"
                ;;
        --param|-include|-o)
		nocodecov_args="$nocodecov_args $i"
		wantcodecov_args="$wantcodecov_args $i"
                lastdash=true
                skipnext=true
                ;;
	-s|-E)
		exec $cmd $@
		;;
        -*)
		nocodecov_args="$nocodecov_args $i"
		wantcodecov_args="$wantcodecov_args $i"
                lastdash=true
                skipnext=false
                ;;
        *)
                if test $lastdash = true -a $skipnext = false
                then
                        echo This is the file '===>' "$i" '<==='
			case "$i" in 
			*.o|*.S|*.s)
				exec $cmd $@
				;;
			*.*)
				;;
			*)
				exec $cmd $@
			esac
                        # See if code coverage applies to this file.
                        if test "$CODECOV_FILE" != "" -a -s "$CODECOV_FILE" && \
                           (echo "$i" | egrep -q -f "$CODECOV_FILE")
                        then
				if test -z "$wantcodecov"
				then
					debug=`basename $i .c`
				elif test $debug = unk
				then
					debug=multi$$
				fi
				wantcodecov="$wantcodecov $i"
			else
				nocodecov="$nocodecov $i"
                        fi
		else
			nocodecov_args="$nocodecov_args $i"
			wantcodecov_args="$wantcodecov_args $i"
                fi
                lastdash=false
                skipnext=false
                ;;
        esac
done

if test ! -z "$wantcodecov"
then
	echo $cmd $@ > $debug.cmd
        eval `$cmd -###  -D__CODECOV $wantcodecov_args $wantcodecov 2>&1 | grep '^ ' | sed -e 's/|/ > $debug.s || exit $?; isi_codecov < $debug.s > $debug..s || exit $?;/' -e '/\/as"/s/$/< $debug..s || exit $?/'`
fi
if test ! -z "$nocodecov"
then
	if test -z "$wantcodecov"
	then
		exec $cmd $@
	fi
        # Default to the normal command
        $cmd $nocodecov_args $nocodecov || exit $?
fi
