#!/bin/sh -f
#
# cmake substitutes  definitions to come up with a 
# semi-valid test script
# 
if test "$SHL_EXT" = ""; then
    SHL_EXT=".so"
fi
if test "$OBJ_EXT" = ""; then
    OBJ_EXT=".o"
fi

if test "$EXE_EXT" = ""; then
    EXE_EXT=""
fi

export SHL_EXT
export OBJ_EXT
export EXE_EXT

export ELMER_LIB="/usr/lib/elmersolver/lib"
export ELMER_INCLUDE="/usr/lib/elmersolver/include"
export ELMER_GRID="/usr/bin/ElmerGrid"
export ELMER_SOLVER="/usr/bin/ElmerSolver"
export ELMER_MESH2D="/usr/bin/Mesh2D"
# @TODO: LD_LIBRARY_PATH works only in unix
export LD_LIBRARY_PATH=".:/usr/lib/elmersolver/lib:/usr/lib:$LD_LIBRARY_PATH"
export PATH=$ELMER_HOME/bin:$PATH

#
# Autoconf substitutes these variables with correct values.
#
#export F90="  $ELMER_INCLUDE"
#export LD="   "
export LD=elmerld
export F90=elmerf90
export LIBS="-L$ELMER_LIB "

# @TODO: -m works only in unix
if [ -w . ] ; then
  /usr/bin/cc -o findnorm$EXE_EXT findnorm.c -lm
  chmod 775 findnorm$EXE_EXT
  export FINDNORM=`pwd`/findnorm$EXE_EXT
else
  /usr/bin/cc -o /tmp/findnorm$EXE_EXT findnorm.c -lm
  chmod 775 /tmp/findnorm$EXE_EXT
  export FINDNORM=/tmp/findnorm$EXE_EXT
fi
total=0
passed=0

if test "$1" = ""; then
   dirs=`find . -type d |sed -e 's/\// /g' |awk '{print $2}' |uniq |grep -v CVS | grep -v .svn | sort`
else
  if test "$1" = "-r"; then
    dirs=`find . -type d |sed -e 's/\// /g' |awk '{print $2}' |uniq |grep -v CVS | grep -v .svn | sort -r`
  else
    dirs="$*"
  fi
fi

cputime="0"
for dir in $dirs; do

      total=`expr $total + 1`
      cwd=`pwd`
      if [ -w $dir ] ; then
	cd $dir
	testdir=$dir
      else
	cp -r $dir /tmp
	cd /tmp/$dir
	testdir=/tmp/$dir
      fi
      printf "test $total : %25s " $dir
      make  > test.log 2>&1

      success=`grep "ALL DONE" test.log | wc -l`
      if test $success -ge 1; then
	  success=`$FINDNORM test.log`
	  cputime=`$FINDNORM test.log $cputime`
      fi

      if test $success -ge 1; then
	  passed=`expr $passed + 1`
          printf "		[PASSED], CPU time=$cputime\n"
	  make -i clean > /dev/null 2>&1
      else
          printf "look at [%s/test.log] for details\n" $testdir
      fi
      cd $cwd
done

echo "Tests completed, passed: $passed out of total $total tests"
echo "Cumulative CPU time used in test: $cputime s"
