#!/usr/bin/env bash

logfile=tests.log
passed=0
failed=0

rm $logfile
rm -r out
mkdir out
stack build

ulimit -t 10

for f in inputs/*.in; do
    echo "Testing $f" >> $logfile

    filename=$(basename "$f" .in)

    parseFile=expected/$filename.parse
    if [ -f $parseFile ]; then
        echo "  Parsing ... " >> $logfile
        if stack exec oh-my-gadt-exe -- -p < $f > out/$filename.parse 2>&1 ; then
            if diff -wB out/$filename.parse expected/$filename.parse > /dev/null ; then
                echo "  ... SUCCESS" >> $logfile
                rm out/$filename.parse
                passed=$(($passed + 1))
            else
                echo "  ... FAILED (incorrect output)" >> $logfile
                failed=$(($failed + 1))
            fi
        else
            echo "  ... FAILED (parsing failed)" >> $logfile
            failed=$(($failed + 1))
        fi
    fi

    typeFile=expected/$filename.type
    if [ -f $typeFile ]; then
        echo "  Type checking ... " >> $logfile
        if stack exec oh-my-gadt-exe -- -t < $f > out/$filename.type 2>&1 ; then
            if diff -wB out/$filename.type expected/$filename.type > /dev/null ; then
                echo "  ... SUCCESS" >> $logfile
                rm out/$filename.type
                passed=$(($passed + 1))
            else
                echo "  ... FAILED (incorrect output)" >> $logfile
                failed=$(($failed + 1))
            fi
        else
            echo "  ... FAILED (type checking failed unexpectedly)" >> $logfile
            failed=$(($failed + 1))
        fi
    fi

    typeFile=expected/$filename.type-fail
    if [ -f $typeFile ]; then
        echo "  Type checking ... " >> $logfile
        if stack exec oh-my-gadt-exe -- -t < $f > out/$filename.type-fail 2>&1 ; then
            echo "  ... FAILED (succeeded but should have failed)" >> $logfile
            failed=$(($failed + 1))
        else
            echo "  ... SUCCESS (failed as expected)" >> $logfile
            rm out/$filename.type-fail
            passed=$(($passed + 1))
        fi
    fi

    evalFile=expected/$filename.eval
    if [ -f $evalFile ]; then
        echo "  Evaluation ... " >> $logfile
        if stack exec oh-my-gadt-exe -- -e < $f > out/$filename.eval 2>&1 ; then
            if diff -wB out/$filename.eval expected/$filename.eval > /dev/null ; then
                echo "  ... SUCCESS" >> $logfile
                rm out/$filename.eval
                passed=$(($passed + 1))
            else
                echo "  ... FAILED (incorrect output)" >> $logfile
                failed=$(($failed + 1))
            fi
        else
            echo "  ... FAILED (eval failed unexpectedly)" >> $logfile
            failed=$(($failed + 1))
        fi
    fi
done

echo "Passed $passed out of $(($passed + $failed)) tests" | tee -a $logfile
