#!/bin/sh

set -e


if [ -z "$MPV_MPRIS_TEST_LOG" ] ; then
        MPV_MPRIS_TEST_LOG=.
fi


test="$1"
exit_code="$MPV_MPRIS_TEST_LOG/$test.exit-code.log"
stderr="$MPV_MPRIS_TEST_LOG/$test.stderr.log"


rm -f "$exit_code" "$stderr"


# This construct directs stderr to what it currently is
# but also sends it to a file for checking afterwards
# and also saves the exit code to a file for checking.
exec 3>&1
{
	ret=0
	"./$test" 2>&1 >&3 ||
	ret=$?
	echo "$ret" > "$exit_code"
} |
tee "$stderr"


< "$exit_code" read -r ret


if [ -s "$stderr" ] ; then
	if [ -z "$MPV_MPRIS_TEST_NO_STDERR" ] ; then
		echo "test $test: stderr not empty!" >&2
		echo "test $test: start of stderr ---------------------" >&2
		cat "$stderr" >&2
		echo "test $test: end of stderr -----------------------" >&2
	fi
	echo "test $test: stderr not empty!" >&2
fi

if [ "$ret" -ne 0 ] ; then
	echo "test $test: failed with exit code $ret" >&2
fi


if [ "$ret" -ne 0 ] ; then
	 exit "$ret"
fi

if [ -s "$stderr" ] ; then
	 exit 1
fi
