#!/usr/bin/env bash
#
# ggcov - A GTK frontend for exploring gcov coverage data
# Copyright (c) 2004-2005 Greg Banks <gnb@users.sourceforge.net>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# 
# $Id: runtest,v 1.9 2010-05-09 05:37:15 gnb Exp $
#

TESTS=
SUPPRESS=
GIVEN=no
SHELL=bash

usage ()
{
    echo "Usage: runtest [test...]"
    exit 1
}

istest ()
{
    test -d "$1" -a -f "$1/runtest"
}

addtest ()
{
    GIVEN=yes
    if istest $1 ; then
    	TESTS="$TESTS $1"
    else
    	echo "$0: warning: no such test \"$1\""
    fi
}

issuppressed ()
{
    local t

    for t in $SUPPRESS ; do
    	[ $t = $1 ] && return 0
    done
    return 1
}

addsuppress ()
{
    if istest $1 ; then
    	SUPPRESS="$SUPPRESS $1"
    else
    	echo "$0: warning: no such test \"$1\""
    fi
}

while [ $# -gt 0 ] ; do
    case "$1" in
    test???)
    	addtest $1
	;;
    [0-9]|[0-9][0-9]|[0-9][0-9][0-9])
    	addtest test`printf %03d $1`
	;;
    \!test???)
    	addsuppress ${1#!}
	;;
    \![0-9]|\![0-9][0-9]|\![0-9][0-9][0-9])
    	addsuppress test`printf %03d ${1#!}`
	;;
    -*)
    	echo "Unknown option \"$1\""
    	usage
	;;
    *)
    	usage
	;;
    esac
    shift
done

if [ $GIVEN = no ] ; then
    TESTS=`ls test[0-9][0-9][0-9]/runtest 2>/dev/null | sed -e 's|/runtest||g'`
fi

T2=
for t in $TESTS ; do
    issuppressed $t || T2="$T2 $t"
done
TESTS="$T2"

# echo TESTS=\"$TESTS\"
# exit 1

echo "Running tests"
(
    echo "hostname: \"`hostname`\""
    echo "date: \"`date +%Y%m%dT%H%M%S`\""
    echo "uname -s: \"`uname -s`\""
    echo "uname -m: \"`uname -m`\""
    echo "uname -r: \"`uname -r`\""
    for f in /etc/*-release _dummy ; do
        [ $f = _dummy ] || echo "head -1 $f: \"`head -1 $f 2>/dev/null`\""
    done
    echo "which gcc: \"`which gcc`\""
    echo "gcc --version: \"`gcc --version | head -1`\""
    echo "which g++: \"`which g++`\""
    echo "g++ --version: \"`g++ --version | head -1`\""
)

NPASS=0
for t in $TESTS ; do
#     echo -n $t
    (
# 	echo "==== $t start"
    	cd $t
	$SHELL runtest
    )
    if [ $? = 0 ]; then
	NPASS=`expr $NPASS + 1`
    fi
    NRUN=`expr $NRUN + 1`
done

echo "Total: $NPASS/$NRUN tests passed"
if [ $NPASS -lt $NRUN ] ; then
    exit 1
else
    exit 0
fi
