#! /bin/sh
# Shell script to run test suite.

if [ x"$1" = x"-v" ]; then VERBOSE=1; shift; fi
if [ x"$1" = x"-v" -o x"$1" = x"-vv" ]; then VERBOSE=1; EXTRA_ARGS=-x; shift; fi

# Creates a temporary file and exports the name of the file to
# the provided argument.  Exits on error.
# 
# Usage: create_tempfile TEMPFILE
#
create_tempfile()
{
    if test $# = 0
    then
       echo "No argument passed to create_tempfile()"
       exit 1
    fi

    if [ -x /bin/tempfile ]
    then
        # Debian 
        export $1="`tempfile`"
    elif [ -x  /bin/mktemp ]
    then
        # RedHat et. al.
        export $1="`mktemp /tmp/modtest.XXXXXX`"
    else
        echo "Don't know how to make a temporary file on this "
        echo "system, sorry."
        exit 1
    fi

    if [ $? -ne 0 ]
    then
        echo "Can't create temporary file."
        exit 1
    fi
}
export -f create_tempfile

# Create testing versions.
make CFLAGS="-DJUST_TESTING -g -Wall" clean all

# Create endianness links
case `file modprobe` in
*MSB*) ENDIAN=be;;
*LSB*) ENDIAN=le;;
*) echo Unknown endian! >&2; exit 1;;
esac
ln -sfn 64-$ENDIAN tests/data/64
ln -sfn 32-$ENDIAN tests/data/32

# Make it easy to run the right ones.
PATH=`pwd`:$PATH

# By default, we want to look like a new kernel.
MODTEST_UNAME=2.5.52
MODTEST_OVERRIDE0=/proc/ksyms
MODTEST_OVERRIDE_WITH0=/proc/nonexistent-file

export MODTEST_UNAME MODTEST_OVERRIDE0 MODTEST_OVERRIDE_WITH0

for dir in `find tests/* -type d | sort`
do
    # data and tmp dirs don't contain tests.
    case "$dir" in tests/data*) continue;; tests/tmp*) continue;; esac

    echo Running tests for $dir.
    shopt -s nullglob
    if [ x"$1" != x ]; then WILDCARD=$dir/$1*; else WILDCARD=$dir/[0-9]*; fi
    for f in $WILDCARD; do
	# Ignore backups dir.
	case "$f" in *~) continue;; esac

	rm -rf tests/tmp/*
        if sh -e $EXTRA_ARGS $f $START_FILE; then
	    [ -z "$VERBOSE" ] || echo Tests $f succeeded.
	else
	    echo Test for $f failed.
	    # Dangerous to leave these lying around
	    make clean >/dev/null
	    exit 1
	    FAILED=1
	fi
    done
done

exit $FAILED
