#! /usr/bin/env bash
#
# General utility to run tests
#
#================================================================
#
# Input flags for this script (./run.sh FLAG): 
#
MANUAL=" 
 Usage
   run.sh [-h,--help] [-l,--list] [-v,--verbose] [-a,--all] [-c,--clean] [<tests>]

 run deviceXlib tests
 When the command line is empty the following manual page is printed:
 
 -h,--help       print this manual    
 -l,--list       print the list of existing tests
 -v,--verbose    print verbose output
 -a,--all        run all tests
 -c,--clean      clean tests outputs
 <tests>         a list of the tests to run (eg 'linalg' 'memcpy' )

"
#
#================================================================
#
# List of tests
#
TEST_LIST=" 
 Tests:

   linalg        Linear algebra wrappers
   malloc        Memory allocations on GPUs
   mapping       Memory mapping (HOST/DEV)
   buffer        Buffers on GPU memory 
   memcpy        Memory copies
   memcpy_async  Memory copies (Async)
   memset        Memory init
   pinned        Handling of pinned memory
"
#
#================================================================
#
testdir=`echo $0 | sed 's/\(.*\)\/.*/\1/'`
bindir=$testdir/../bin
bold_on="[1m"
bold_off="[0m"
#
# parse command line input
#
LIST=
CLEAN=
VERBOSE=
#
for OPT in $*
do
  case $OPT in
  ("-h" | "--help") echo "$MANUAL" ; exit 0 ;;
  ("-l" | "--list") echo "$TEST_LIST" ; exit 0 ;;
  ("-a" | "--all")      LIST="ALL" ;;
  ("-v" | "--verbose")  VERBOSE="yes" ;;
  ("-c" | "--clean")    CLEAN="yes" ;;
  (*)                   LIST="$LIST $OPT" ;;
  esac
done
# 
if [ "$CLEAN" = "yes" ] ; then rm -f $testdir/*.out ; exit 0 ; fi
#
if [ "$LIST" == "ALL" ] ; then
   LIST=`echo "$TEST_LIST" | awk '{ if (NR<=3) {next} else {print $1} }'`
fi
if [ -z "$LIST" ] ; then echo "$MANUAL" ; exit 0 ; fi

#
# reporting
#
echo "
${bold_on}Running tests:${bold_off} 
"
ind=0
for mytest in $LIST ; do
  var=$((ind++))
  echo "  ($ind)  $mytest"
done
echo

#
# perform the required tasks
#
for mytest in $LIST
do
    testfile=$bindir/test_${mytest}.x    
    output=$testdir/test_${mytest}.out
    #
    if [ ! -x $testfile ] ; then
        echo "  file $testfile does not exist" ; exit 3
    fi
    # 
    # running test 
    #
    echo
    echo " Running ${bold_on}${mytest}${bold_off}"
    #
    $testfile > $output
    if [ "$VERBOSE" = "yes" ] ; then cat $output | grep -v "\#" ; fi
    cat $output | grep '\#' | awk -f $testdir/fmt_output.awk
    #
done

echo
exit 0





