#!@SH_PROG@ -f
# -*- shell-script -*-

export srcdir=@abs_srcdir@
[ -z "$SH" ] && export SH=@SH_PROG@

export top_builddir=@abs_top_builddir@
export top_srcdir=@abs_top_srcdir@
export abs_top_srcdir=@abs_top_srcdir@
export host_os=@host_os@

check_output() {
  typeset testfile="$1"
  typeset rightfile="$2"
  # Bourne sh
  # set -o noglob

  @DIFF@ @DIFF_OPTS@ "$testfile" "$rightfile" && rm -f "$testfile"
  return $?
}

# http://stackoverflow.com/questions/5451297/exit-code-when-crashed
check_exit_status ()
{
    local status="$?";
    local msg="";
    local signal="";
    if [ ${status} -ne 0 ]; then
        if [ $((${status} < 128)) -ne 0 ]; then
            msg="exit (${status})";
        else
            signal="$(builtin kill -l $((${status} - 128)) 2>/dev/null)";
            if [ "$signal" ]; then
                msg="kill -$signal$msg";
            fi;
        fi;
        # want this to go to stdout to be captured
        echo "INVESTIGATE EXIT FAILURE: [${status} => ${msg}]";
    fi;
    return 0
}

run_debugger_opts="-B -q --no-init --no-highlight"
# Run the debugger on test program $1 with (optional) debugger options $2
# using commandfile $3. We assume $TOP_BUILDDIR, $TOP_SRCDIR and
# $TEST_NAME have been set previously
run_debugger() {
  typeset debugged_script="$1"
  typeset dbg_opts=${2:-"-L ${top_srcdir} $run_debugger_opts"}
  [[ -z $short_test_name ]] && short_test_name=$TEST_NAME
  typeset cmdfile=${3:-"${top_srcdir}/test/data/${short_test_name}.cmd"}
  $SH -- ${top_builddir}/@PACKAGE@ $dbg_opts -x "$cmdfile" "$debugged_script" $ARGS
  check_exit_status
}

ARGS=''

# Some tests-* scripts use the below
TEST_FILE="${top_builddir}/test/integration/${TEST_NAME}.check"
RIGHT_FILE="${top_srcdir}/test/data/${TEST_NAME}.right"
TEST_FILTERED_FILE="/tmp/${TEST_NAME}-filtered.check"
RIGHT_FILTERED_FILE="/tmp/${TEST_NAME}-filtered.right"

run_test_check() {
    short_script_name=${1:-$TEST_NAME}
    short_test_name=${2:-$TEST_NAME}
    debugged_script=${3:-"${top_srcdir}/test/example/${short_script_name}.sh"}

    # Reassign variables to allow overrides via the above parameters
    TEST_FILE="${top_builddir}/test/integration/${short_test_name}.check"
    RIGHT_FILE="${top_srcdir}/test/data/${short_test_name}.right"
    TEST_FILTERED_FILE="/tmp/${short_test_name}-filtered.check"
    RIGHT_FILTERED_FILE="/tmp/${short_test_name}-filtered.right"

    [[ ! -r $debugged_script ]] && \
	debugged_script="${top_builddir}/test/example/${short_script_name}.sh"
    if [[ -z "$srcdir" ]] ; then
	print -r -- "You need to set srcdir before running this."
	exit 10
    fi
    (cd $srcdir && run_debugger "$debugged_script" 2>&1 >"$TEST_FILE" </dev/null)
    check_output "$TEST_FILE" "$RIGHT_FILE"
    # Return code tells testing mechanism whether passed or not.
    return $?
}
