#!/bin/bash -ex

if [ x"$AUTOPKGTEST_TMP" = x ] ; then
	# Create a temporary directory and clean it up when done.
	export AUTOPKGTEST_TMP="`mktemp -d`"
	cleanup() {
		rm -rf "$AUTOPKGTEST_TMP"
	}
	trap cleanup EXIT
fi

# Make sure we have a home during the test.
export HOME="$AUTOPKGTEST_TMP/home"
mkdir -p "$HOME"

# If there is no DISPLAY, create one for this test.
if [ x"$DISPLAY" = x ]; then
	exec xvfb-run "$0" "$@"
fi

# Run openmsx and store the (stderr) output in a file, in addition to showing it to the user.
openmsx 2>&1 | tee "$AUTOPKGTEST_TMP/output" &

# Wait for emulator to start up.
sleep 3

# Print a string to stderr, then exit using ctrl-break.
xvkbd -xsendevent -window 'openMSX*' -text '\{F10}puts stderr "autopkgtest output"\r\D3quit\r'

# Wait for the emulator to exit.
sleep 3

# Kill the emulator if it was still running.
# Don't care if that worked; without job control this isn't reliable.
kill % || :

# Check that the expected output is produced. If not, that makes the test fail.
if ! grep '^autopkgtest output$' "$AUTOPKGTEST_TMP/output" >/dev/null ; then
	echo >&2 "Emulator did not produce expected output"
	exit 1
fi

exit 0
