#!/bin/bash

# don't print non-matching glob patterns
shopt -s nullglob

# path to ag++
AGCC="$(realpath "../../AspectC++/bin/${TARGET}/ag++${EXT}")"

# summary printed in case at least one testcase failed
REPORT=""
ERR_OCCURED=0;

# check if TARGET variable is set
if [ -z ${TARGET} ];then
  echo -en "\n\nThis script has to be invoked by 'make test' from the toplevel directory\n\n"
  exit
fi

# Create directory for test artifacts
TestRootBuildDir="../build/${TARGET}/test"
rm -rf "${TestRootBuildDir}"
mkdir -p "${TestRootBuildDir}"


# check if the name of a test was passed
if [ $# -gt 0 ];then
  if [ -f "$1.sh" ];then
    TEST_FILES="$1.sh";
  else
    echo "Test file '$1.sh' not found"
    exit;
  fi
else
  # if no test was passed as argument execute all test in this folder
  TEST_FILES=$(find . -maxdepth 1 -name 'test_??.sh' -print0| sort -z | xargs -0)
fi

# directory with tests
TestDir="../../../../tests"
TestSrcDir="${TestDir}/src"

# loop through all test files
for testfile in ${TEST_FILES}
do
  rm -f puma.config
  ERR_MSG=""

  # create directory for test execution 
  TestBuildDir="${TestRootBuildDir}/$(basename "${testfile}" .sh)"
  mkdir -p "${TestBuildDir}"
  pushd "${TestBuildDir}" > /dev/null

  # files for storing output from stdout and stderr
  StdOutFile=stdout.txt;
  StdErrFile=stderr.txt;

  # include testfile file
  source "${TestDir}/$testfile"

  # redirect stdout and stderr
  exec 6>&1;
  exec 7>&2;
  exec > ${StdOutFile}
  exec 2> ${StdErrFile}

  # execute the 'runtest' function of current test file
  runtest
  RET=$?

  # execute main function of current test

   #restore stdout and stderr
  exec 1>&6 6>&-
  exec 2>&7 7>&-

  # check if test succeeded
  if [ $RET == 0 ]; then
    
    # test succeded
    echo -n "."
  
  else 
    
    # test failed
    echo -n "[${testfile/*_/}:F]"
    ERR_OCCURED=1

    # get stdout and stderr
    STDOUT=`cat ${StdOutFile}`
    STDERR=`cat ${StdErrFile}`
    
    # add information to error summary
    REPORT="${REPORT}\n\n-----------------------------------------------------------------------------------------\n"
    REPORT="${REPORT}TESTFILE: ${testfile}\n"
    REPORT="${REPORT}-----------------------------------------------------------------------------------------\n\n"
    REPORT="${REPORT}TEST DESCRIPTION: ${DESC//'\\'/\\\\}\n"
    REPORT="${REPORT}-----------------\n\n"
    REPORT="${REPORT}ERROR: ${ERR_MSG//'\\'/\\\\}\n"
    REPORT="${REPORT}------\n\n"
    REPORT="${REPORT}STDOUT:\n"
    REPORT="${REPORT}-------\n${STDOUT//'\\'/\\\\}\n"
    REPORT="${REPORT}STDERR:\n"
    REPORT="${REPORT}-------\n${STDERR//'\\'/\\\\}\n"

  fi

  # leave test build dir
  popd > /dev/null
done

# print summary of all errors occured
echo;
echo;
if [[ ( $ERR_OCCURED == 1 ) || ( $VERBOSE == 1 ) ]];then
   echo -e "${REPORT}"
fi 

if [[ $ERR_OCCURED == 0 ]];then
  echo "All tests OK"
fi


