# /bin/sh

###################
###  Constants  ###
###################

lwd=`pwd`
test_language='test_language'
input='input'
output='output'
output_ref=$output.ref
output_dif=$output.dif

########################
###  Default values  ###
########################

test_dir=tests
bin_dir=$lwd/bin


###############
###  Usage  ###
###############

usage ()
{
   echo << EOF
Usage: run_tests.sh [options]

Options:
  -t <dir>
  --testdir <dir>  Use <dir> as the directory contains the tests to be run
                   
EOF
}


##########################################
###  Command line switches processing  ###
##########################################

while [ "x$1" != 'x' ]
do
   case "$1" in
      -b|--bin_dir)
         if [ "x$2" = 'x' ]
         then
            echo "Error: missing bin directory name after '$1' switch"
            usage
            exit 1
         fi
         bin_dir=$lwd/$2
         shift; shift
         ;;
      -t|--test_dir)
         if [ "x$2" = 'x' ]
         then
            echo "Error: missing test directory name after '$1' switch"
            usage
            exit 1
         fi;
         test_dir=$2
         shift; shift
         ;;
      *)
         echo "Invalid switch: '$1'"
         usage
         exit 1
         ;;
   esac
done

######################
###  Main program  ###
######################

if [ ! -d $test_dir ]
then
   echo "Error: $test_dir is not a directory."
   exit 1
fi

list_of_tests=`find $test_dir -name $input -print`


nb_tests=0;    typeset -i nb_tests
nb_passed=0;   typeset -i nb_passed
nb_failed=0;   typeset -i nb_failed

for input_file in $list_of_tests
do
   nb_tests=$nb_tests+1
   current_dir=`dirname $input_file`
   current_file=`cat $input_file`

   echo '----------------------------------------------------------------'
   echo "--  Testing $current_file in $current_dir..."
   echo '----------------------------------------------------------------'
   echo '--'

   $bin_dir/$test_language $current_dir/$current_file \
      > $current_dir/$output 2>&1

   diff -c $current_dir/$output_ref $current_dir/$output \
      > $current_dir/$output_dif
   
   if [ -s $current_dir/$output_dif ]
   then
      nb_failed=$nb_failed+1
      echo '*** Result => FAIL'
      echo
      echo 'Diff follows:'
      echo '<<'
      cat $current_dir/$output_dif
      echo '>>'
   else
      nb_passed=$nb_passed+1
      echo '+++ Result => PASS'
   fi
   echo

   ### Remove all the files that we created
   rm -f $current_dir/$output
   rm -f $current_dir/$output_dif
done

echo '----------------------------------------------------------------'
echo "--  Test results:"
echo '--'
echo "--  Number of tests: $nb_tests"
echo "--          Nb PASS: $nb_passed"
echo "--          Nb FAIL: $nb_failed"
echo '--'
echo '----------------------------------------------------------------'

