#!/bin/bash
set -e

pkg="gdpc"

if [ "$AUTOPKGTEST_TMP" = "" ] ; then
  AUTOPKGTEST_TMP=`mktemp -d /tmp/${pkg}-test.XXXXXX`
  trap "rm -rf $AUTOPKGTEST_TMP" 0 INT QUIT ABRT PIPE TERM
fi

check_n_cleanup () {
	local gdpc_pids="$(
		ps aux \
		| awk "/^$USER"'.*bin[/]gdpc/ {print$2}' \
		| xargs
	)"

	local xvfb_pids="$(
		ps aux \
		| awk -vORS=' ' "/^$USER"'.*[X]vfb/ {print$2}' \
		| xargs
	)"

	if [ -n "$gdpc_pids" ]
	then
		kill $gdpc_pids
	else
		printf -- 'error: gdpc crashed before the end of the test\n' >&2
		exit 1
	fi
	test -n "$xvfb_pids" && kill $xvfb_pids
}

cp -a /usr/share/doc/${pkg}/examples/* $AUTOPKGTEST_TMP

cd $AUTOPKGTEST_TMP

gunzip *.gz

rm -f test.log
set -v
#test recipe from README file
xvfb-run --auto-servernum \
	/usr/bin/gdpc 2>&1 \
	| tee --append test.log &
sleep 10
check_n_cleanup

xvfb-run --auto-servernum \
	/usr/bin/gdpc cube 30 m 2 d 20 erase 1 2 3 4 liquid.test 2>&1 \
	| tee --append test.log &
sleep 10
check_n_cleanup

xvfb-run --auto-servernum \
	/usr/bin/gdpc m 2 d 10 erase xyz 2 3 4 5 md.test 2>&1 \
	| tee --append test.log &
sleep 10
check_n_cleanup

xvfb-run --auto-servernum \
	/usr/bin/gdpc m 2 d 10 erase usetypes xyz 2 3 4 5 manytypes.test 2>&1 \
	| tee --append test.log &
sleep 10
check_n_cleanup
set +v

ls -l test.log
cat test.log

echo "PASS"
