#!/bin/sh

## exclusion list for faust and C++ errors
XLIST1="faust2md faust2atomsnippets"
XLIST2="faust2md faust2atomsnippets faust2eps faust2firefox faust2graph faust2graphviewer faust2mathdoc faust2mathviewer faust2sig faust2sigviewer faust2svg faust2juce"

## test exclusion : notinlist "toto" "a b c d e" -> true
notinlist() {
    for word in $2; do
        if [ $word = $1 ]; then
            return 1
        fi
    done
    return 0
}

runtest() {
    # usage: runtest <logfile> <cmd> <arg1> ...
    local logfile=$1
    shift
    ("$@" >"${logfile}" 2>&1) && echo "OK: '$@' succeeded!" || echo "ERROR: '$@' failed"
    rm -rf good good-faustnode
}

runtestfail() {
    # usage: runtestfail <logfile> <cmd> <arg1> ...
    local logfile=$1
    shift
    ("$@" >"${logfile}" 2>&1) && echo "ERROR: '$@' shouldn't have succeeded!" || echo "OK: '$@' correctly failed"
    rm -rf good good-faustnode
}

runtestref() {
    # usage: runtestref <logfile> <name> <refbasename> <cmd> <arg1>...
    local logfile=$1
    local name=$2
    local referencefile="${3}_ref.txt"
    local resultfile="${3}.txt"
    shift 3
    if ("$@" >"${logfile}" 2>&1); then
        "./${name}" > "${resultfile}"
        diff "${resultfile}" "${referencefile}" && echo "OK: '$@' succeeded!" || echo "ERROR: '$@' failed (mismatched output)"
    else
        echo "ERROR: '$@' failed"
    fi
    rm -f "${resultfile}"
    rm -rf "${name}"
}

PATH=../../build/bin:$PATH
faust --version || exit $?
echo location $(command -v faust)

######################################################
## Test all scripts for faust errors and c++ errors ##
######################################################
# All scripts must correctly detect and report faust
# errors and C++ errors.
#
echo
echo "Check Faust errors are correctly detected/reported"
echo
for S in ../../tools/faust2appls/faust2*; do
    scriptname=$(basename $S .in)
    if notinlist $scriptname "$XLIST1"; then
        runtestfail LOG "${scriptname}" badfaust.dsp
    fi
done

echo
echo "Check C++ errors are correctly detected/reported"
echo
for S in ../../tools/faust2appls/faust2*; do
    scriptname=$(basename $S .in)
    if notinlist $scriptname "$XLIST2"; then
        runtestfail LOG "${scriptname}" badcpp.dsp
    fi
done
