#!/bin/bash

export valgrind=env

for opt in ${*}
do
case "$opt" in
(--valgrind) valgrind="valgrind --leak-check=full --show-reachable=yes" ;;
(*) echo error ; exit ;;
esac
done

{

date
echo "Running regtest in $(pwd)"

if [ "$valgrind" = valgrind ] ; then
echo "using valgrind"
fi

rm -fr tmp
mkdir tmp
cd tmp
cp -f ../* .

test -f config || {
  echo "FAILURE: config not found"
  exit 1
}

mpiprocs=0

source ./config

for file in $extra_files
do
  cp -f ../$file .
done

echo "++ Test type: $type"
echo "++ Arguments: $arg"
echo "++ Processors: $mpiprocs"

mpi=env
plumed=plumed

root=$($plumed --no-mpi info --root)

if test -z "$root" ; then
  echo "FAILURE: plumed executable not available"
  exit 1
fi

cd ../../../../
if [[ "${PWD}"/ != "$root" ]] ; then
echo "WARNING using plumed from $root"
fi
cd -


if ((mpiprocs>0)); then
mpi="${PLUMED_MPIRUN:-mpirun} -np $mpiprocs"

if ! plumed --has-mpi
then
  echo "NOT_APPLIABLE (MPI NOT INSTALLED)"
  exit 0;
fi

else

plumed="plumed --no-mpi"

fi

if ((mpiprocs>0)) && [[ "$valgrind" != "env" ]]
then
  echo "NOT_APPLIABLE (MPI cannot be used with valgrind)"
  exit 0;
fi

for need in $plumed_needs
do
  echo "Checking for $need"
  if ! $plumed --has-$need
  then
    echo "NOT_APPLIABLE ($need NOT INSTALLED)"
    exit 0;
  fi
done

case "$type" in
(simplemd)
  test -f in || {
    echo "FAILURE: in file not present"
    exit 1
  }
  echo "Run simplemd"
  $mpi $valgrind $plumed simplemd < in > out 2> err
  ;;
(driver)
  echo "Run driver"
  $mpi $valgrind $plumed driver $arg > out 2> err
  ;;
(sum_hills)
  echo "Run driver"
  $mpi $valgrind $plumed sum_hills $arg > out 2> err
 ;;
(make)
  echo "Run Make"
  $plumed info --configuration > Makefile.conf
  $plumed --is-installed || ln -s $($plumed info --root)/src plumed
  cat <($plumed info --configuration) $($plumed info --root)/src/lib/Plumed.inc.static ../../../scripts/exe.make > Makefile 
  make exe 1>out 2> err
  $mpi $valgrind ./exe $arg >> out 2>> err
 ;;
(*) echo "unknown test type" ; exit 1 ;;
esac

if type -t plumed_regtest_after 1>/dev/null ; then
  plumed_regtest_after
fi

echo "Done. Here is the error file:"
cat err


if ls *.reference > /dev/null
then
for file in *.reference ; do
  new="${file%.reference}"
  if test -f "$new" ; then
    ../../../scripts/fixzeroes.sh "$file"
    cp "$new" "$new.zfix"
    ../../../scripts/fixzeroes.sh "$new.zfix"
    out="$(diff "$file" "$new.zfix")"
    test -n "$out" && {
      echo FAILURE
      echo "Diff for ${file%.reference}:"
      diff "${file}" "$new.zfix"
    }
  else
    echo FAILURE
    echo FILE $new does not exist
  fi
done
else
    echo WARNING
    echo no file has been checked
fi


cd ../

} | tee report.txt
