#!/bin/sh

while echo $1 | grep -q =; do
    echo "$1"
    eval "export $1"
    shift
done

test -d "$TOOLS" -a -f "$TOOLS/divine" || {
    echo "TOOLS has to be directory with your divine binary."
    exit 1
}

if echo $TOOLS | grep -q "^C:"; then # MSYS hack
    TOOLS=`echo -n "$TOOLS" | sed -e 's,C:,/c,;s,\\\\,/,;'`
fi
PATH="$TOOLS:$PATH"

# fake ssh for mpiexec
cat > $TOOLS/ssh <<EOF
#!/bin/sh
test "\$1" = "-x" && shift
shift # hostname
eval "\$@"
EOF
chmod +x $TOOLS/ssh

if test -z "$MPIEXEC"; then
    MPIEXEC=false
else
    MPIEXEC=$(readlink -f `which $MPIEXEC`)
fi


tests="$@"
good=0
goodsub=0
skipcount=0
ran=0

mkdir -p results
echo -n > results/list
for t_ in $tests; do
    # cut+rev is nicer but the latter's in util-linux
    t=`echo $t_ | sed -e 's,.*/\([^/]\+/[^/]\+\)$,\1,'`
    test -n "$T" && {
        echo $t | grep -q $T || continue
    }
    ran=$(($ran + 1))
    printf "Running %-40s" "$t ..."
    outf=`mktemp output.XXXXXX`
    if test -n "$INTERACTIVE"; then bash $t_ ; else  bash $t_ > $outf 2>&1; fi

    ret=$?
    sub=$(grep -c "^#### PASSED" $outf)
    goodsub=$(($goodsub + $sub))
    if test $ret = 0; then
        result=good
        good=$(($good + 1))
        if test "$sub" -ne 0; then
	    echo " passed $sub subtests."
        else
            echo " passed."
        fi
    elif test $ret = 200; then
        result=skipped
        ran=$(($ran - 1))
        skipcount=$(($skipcount + 1))
        skipped="$skipped $t"
	echo " skipped."
    else
        result=failed
	echo " FAILED!"
	len=`echo $t | wc -c`
	# fancy formatting...
	printf -- "--- Output: $t -"
	for i in `seq $(($len + 14)) 78`; do echo -n "-"; done; echo
        if test -z "$VERBOSE" && test $sub -ne 0; then
            echo "$sub sub-test(s) passed; use VERBOSE=1 to unhide them"
            while grep -q "^#### PASSED" $outf; do sed -e "1,/^#### PASSED/d" -i $outf; done
        fi
        cat $outf
	printf -- "--- End: $t ----"
	for i in `seq $(($len + 14)) 78`; do echo -n "-"; done; echo
	failed="$failed $t"
    fi

    echo "$t $result" >> results/list
    cp $outf "results/$(echo $t | sed -e s,/,_,g).txt"

    rm -f $outf
done

if test -n "$skipped"; then
    echo "Tests skipped:"
    for t in $skipped; do
	printf "\t%s\n" $t
    done
fi

if test -n "$failed"; then
    echo "TESTS FAILED:"
    for t in $failed; do
	printf "\t%s\n" $t
    done
    echo
    echo "== $good out of $ran passed (total of $goodsub subtests passed). $skipcount tests skipped."
    echo
    exit 1
else
    echo
    echo "== All $good tests ($goodsub subtests) passed. $skipcount tests skipped."
    echo
fi
