#!/bin/sh

# shellcheck disable=SC1091
. ././common-setup.sh

# Use absolute path so tests that change working directory still use 
# scripts from parent directory.  Note that using $PWD seems to fail
# here under Gitlab's CI environment.
PATH=$(realpath ..):$(realpath .):${PATH}

experimental=""
serial=""
mode=diffing
log=""
while getopts bhl:nosx opt
do
    case $opt in
	b) mode=build;; 
	l) log="log $OPTARG" ;;
	n) mode=errs;;
	o) mode=view;;
	s) serial="set serial";;
	x) experimental="set experimental";;
	*) cat <<EOF
singletest - run a single regression test

The REPOSURGEON environment variable can be used to substitute in a
different implementation.

With -b. regenerate the corresponding check file

With -h, display this option summary.

With -l, set log bits (only with -o)

With -n, pass out stderr but consume stdout.

With -o, dump the test output rather than diffing against the checkfile

With -s, set the serial flag to disable parallelism

With -x, set the experimental flag.
EOF
	   exit 0;;
    esac
done
# shellcheck disable=SC2004
shift $(($OPTIND - 1))

# shellcheck disable=SC2068
for x in $@;
do
    what=$(echo "${x}" | sed -e '/-FAILED/s///' -e '/.tst/s///')

    if [ -f "${what}.tst" ]
    then
	tst="${what}.tst"
	chk="${what}.chk"
    elif [ -f "${what}.tst-FAIL" ]
    then
	tst="${what}.tst-FAIL"
	chk="${what}.chk"
	echo "Expect a diff"
    elif [ -z "${what}" ]
    then
	exec "$0" -h
	exit 1
    else
	echo "No script matching ${what} found"
	exit 1
    fi
    # This redirect to stderr is so this script can be used to rebuild checkfiles
    (grep '^##' "${tst}" 2>/dev/null) 1>&2
    case $mode in
    build) ${REPOSURGEON:-reposurgeon} "set serial" "$experimental" "script ${tst}" >"${chk}" 2>&1 ;;
    view)  ${REPOSURGEON:-reposurgeon} "$log" "$serial" "$experimental" "script ${tst}" 2>&1 ;;
    errs)  ${REPOSURGEON:-reposurgeon} "$serial" "$experimental" "script ${tst}" >/dev/null ;;
    *)     ${REPOSURGEON:-reposurgeon} "$serial" "$experimental" "script ${tst}" 2>&1 | diff -u "${chk}" - ;;
    esac
done

# Return exit status of the last command to run.
# In particular, if the last command was a diff,
# this will return 0 for empty and 1 for nonempty.
# Otherwise you'll typically get the exit status
# of reposurgeon. 
exit $?
