#!/usr/bin/env bash

# This set of scripts expects to run on GNU or OpenBSD.

_show_fail()
{
    mismatch=$1

    echo "Test failed because '$mismatch' does not match"

    for i in actual expected
    do
        echo "$mismatch.$i:"
        printf '['
        cat "$work"/"$mismatch.$i"
        printf ']\n'
        echo
    done

    # That "|| echo" will print an empty separator line only if diff
    # found differences.
    diff -au "$work"/"$mismatch".{actual,expected} || echo

    echo 'work:'
    ls -Ral "$work"
    echo

    global_run_on_fail
}

_check_assumptions()
{
    for i in exitcode stderr stdout
    do
        cmp "$work"/"$i".{actual,expected} || { _show_fail "$i"; exit 1; }
    done

    exit 0
}


tests_total=0
tests_failed=0

if ! . global-setup
then
    cat >&2 <<EOF
Cannot find "global-setup", aborting. This usually happens if you did
not "cd" into the directory that contains your test suite.
EOF
    exit 1
fi

for i in *.test.sh
do
    [[ -r "$i" ]] || continue

    echo "==> $i"

    (
        work=$(mktemp -d)
        global_presetup_per_test

        (
            . "$i"
            test_setup
            test_set_assumptions

            global_run_program

            _check_assumptions
        )
        exitcode=$?

        global_reset_per_test
        rm -Rf -- "$work"

        exit $exitcode
    ) || (( tests_failed++ ))
    (( tests_total++ ))
done

echo "fail $tests_failed, pass $((tests_total - tests_failed)), total $tests_total"

(( tests_failed > 0 )) && exit 1 || exit 0
