#!/bin/bash

# The ability of ctdb_test_env to take tests on the command-line is
# nice, but here we need to hack around it with that colon to reset
# the arguments that it sees.
. $(dirname $0)/ctdb_test_env :

. ctdb_test_functions.bash

usage() {
    cat <<EOF
Usage: run_tests [OPTIONS] [TESTS]

EOF
    exit 1
}

######################################################################

with_summary=false
with_desc=false
quiet=false

temp=$(getopt -n "$prog" -o "xdhqs" -l help -- "$@")

[ $? != 0 ] && usage

eval set -- "$temp"

while true ; do
    case "$1" in
	-x) set -x; shift ;;
	-d) with_desc=true ; shift ;;  # 4th line of output is description
	-q) quiet=true ; shift ;;
	-s) with_summary=true ; shift ;;
	--) shift ; break ;;
	*) usage ;;
    esac
done

if $quiet ; then
    show_progress() { cat >/dev/null ; }
else
    show_progress() { cat ; }
fi

######################################################################

tests_total=0
tests_passed=0
summary=""

rows=$(if tty -s ; then stty size ; else echo x 80 ; fi | sed -e 's@.* @@' -e 's@^0$@80@')
ww=$((rows - 7))

tf=$(mktemp)
sf=$(mktemp)

set -o pipefail

for f; do
    [ -x $f ] || fail "test \"$f\" is not executable"
    tests_total=$(($tests_total + 1))
    ctdb_test_run "$f" | tee "$tf" | show_progress
    status=$?
    if $with_summary ; then
	if [ $status -eq 0 ] ; then
	    tests_passed=$(($tests_passed + 1))
	    t=" PASSED "
	else
	    t="*FAILED*"
	fi
	if $with_desc ; then
	    desc=$(tail -n +4 $tf | head -n 1)
	    f="$desc"
	fi
	echo "$t $f" >>"$sf"
    fi
done

rm -f "$tf"

if $with_summary ; then
    echo
    cat "$sf"
    echo
    echo "${tests_passed}/${tests_total} tests passed"
fi

rm -f "$sf"

test_exit
