#!/bin/bash

nerror=0
nok=0
notapp=0
html=
fail=

for arg
do
case $arg in
  (--html) html=1 ;;
  (--fail) fail=1 ;;
esac
done

echo
echo
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "+ Test session ended at $(date)"

dirs=$(
  ll=$(ls */Makefile)
  ll=${ll///Makefile/ }
  for d in $ll ; do
    for file in $d/rt*/Makefile
    do
      echo ${file%Makefile}
    done
  done
)

file1=$(mktemp -t plumed.XXXXXX)
file2=$(mktemp -t plumed.XXXXXX)

for dir in $dirs
do
  file=${dir}report.txt
  fullname="$file"
  if [ -n "$html" ] ; then
    fullname='<a href="'"$file"'">'"$file"'</a>'
  fi
  if grep -q NOT_APPLICABLE $file ; then
    ((notapp++));
    echo + test $dir NOT APPLICABLE >> $file1
    echo + check file $fullname for more information >> $file1
  elif grep -q FAILURE $file ; then
    ((nerror++))
    echo + ERROR in test $dir >> $file2
    echo + check file $fullname for more information >> $file2
  else
    ((nok++))
  fi
done
cat $file1
cat $file2

echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "+ Final report:"
echo "+ $((nok+nerror)) tests performed, $notapp tests not applicable"
echo "+ $nerror errors found"
if ((nerror==0)) ; then
echo "+ Well done!!"
else
echo "+ Find the bug!"
echo "+ To replace references, go to the test directory and"
echo "+ type 'make reset'"
if [ -n "$fail" ] ; then
  exit 1
fi
fi

if [ "$PLUMED_ALL_TESTS" = yes ] ; then
  if (($notapp>0)) ; then
    echo "+ You are running with PLUMED_ALL_TESTS=yes and some tests are not applicable"
    echo "+ This is likely happening on the first job under TRAVIS-CI"
    echo "+ Please check that all modules have been properly enabled!"
    if [ -n "$fail" ] ; then
      exit 1
    fi
  fi
fi
echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo
echo

