#!/bin/bash

FAIL=
TOPDIR=`pwd`
TMPCHECK=${TOPDIR}/tmpcheck

if [ -d ${TMPCHECK} ]; then
    rm -rf ${TMPCHECK}/*
else
    mkdir ${TMPCHECK}
fi

for t in `find ./tests -name "CMakeLists.txt" | xargs grep smoketests | sed -e 's/^..tests.//' -e 's/.CMakeLists.txt.*//' | grep -v ^CMakeLists.txt`; do
    cd ${TMPCHECK}
    if [ -f ${TOPDIR}/tests/$t/input.dat -o -f ${TOPDIR}/tests/$t/input.py ]; then
        # Skip smoketests that require currently unavailable features
        if `echo $t | egrep -q '(dftd3|v2rdm_casscf|gdma|snsmp2|libefp|gcp.hf3c|dkh|pcmsolver|mrcc|ccsorttransqt2|cfour)'` ; then
            echo "Skipping test ${t}"
            continue
        fi
        echo -n "Running test ${t}... "
        LOGFILE=`basename $t`.log
        mkdir -p $t; cd $t
        cp ${TOPDIR}/tests/$t/* .
        python3 ${TOPDIR}/tests/runtest.py input.* ${LOGFILE} false ${TOPDIR} false output.dat /usr/bin/psi4 > /dev/null
        if [ "$?" -ne 0 ]; then
           FAIL=1
           echo "FAILED"
           echo "LOG:"
           tail -100 ${LOGFILE}
        else
           echo "OK"
        fi
    else
        echo "No input.dat or input.py found for $t, skipping test"
    fi
done

cd ${TOPDIR}

if [ -z "$FAIL" ]; then
    rm -rf tmpcheck
    echo "All tests passed"
    exit 0
else
    echo "Some tests failed"
    exit 1
fi
