#!/bin/sh

# This is a wrapper around adt-run meant to be called from sbuild:
# export DEB_ADT_SUMMARY=$(mktemp /var/tmp/$PACKAGE.XXXXXX.xml)
# sbuild --finished-build-commands='adt-sbuild %SBUILD_BUILD_DIR %SBUILD_PKGBUILD_DIR' ...

# Input:
#  %SBUILD_BUILD_DIR %SBUILD_PKGBUILD_DIR
#  DEB_ADT_SUMMARY (possibly unset)
#  DEB_PG_SUPPORTED_VERSIONS (required)
# Output:
#  xml test results (or dummy result) in DEB_ADT_SUMMARY
# Requirements:
#  sudo DEB_PG_SUPPORTED_VERSIONS=value adt-run

if [ -z "$DEB_ADT_SUMMARY" ]; then
	echo "DEB_ADT_SUMMARY is not set, skipping tests"
	exit
fi

set -eu

if ! test -f "$DEB_ADT_SUMMARY"; then
	"Error: DEB_ADT_SUMMARY=$DEB_ADT_SUMMARY does not exist. It should have been created before invoking sbuild, and put onto a bind-mounted partition (see /etc/schroot/*/fstab)" >&2
	exit 1
fi

SBUILD_BUILD_DIR="$1"
SBUILD_PKGBUILD_DIR="$2"
cd "$SBUILD_PKGBUILD_DIR"

if [ ! -f debian/tests/control ]; then
	echo "Package does not have autopkgtest support (there is no debian/tests/control file)"
	adtsummary2junit /dev/null > $DEB_ADT_SUMMARY
	exit 0
fi

if [ ! -f debian/files ]; then
	echo "Error: Package source is not built, debian/files is missing"
	exit 1
fi

# precise's sudo doesn't remove HOME from the environment, and sbuild's /sbuild-nonexistant confuses adt-run
unset HOME

ADT_SUMMARY=$(mktemp /tmp/adt.XXXXXX.summary)
trap "rm -f $ADT_SUMMARY" 0 2 3 15

(
set -x
sudo DEB_PG_SUPPORTED_VERSIONS="$DEB_PG_SUPPORTED_VERSIONS" \
  adt-run --summary $ADT_SUMMARY \
	$SBUILD_BUILD_DIR/*.deb \
	--built-tree $SBUILD_PKGBUILD_DIR \
	--- adt-virt-null
) || EXIT=$?

case ${EXIT:-0} in
	0|2|4|6|8) # all ok or some test failed, exit 0 here and let adtsummary2junit report the failure to jenkins
		adtsummary2junit $ADT_SUMMARY > $DEB_ADT_SUMMARY
		exit 0
		;;
esac

# in reality, sbuild ignores failures here, but jenkins will complain if the junit xml result file is empty
exit $EXIT
