#!/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 (required)
#  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 "Error: DEB_ADT_SUMMARY is not set. Did you configure sbuild.conf to pass through DEB_*?"
  exit 1
fi

set -eu

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

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

(
if [ -x /usr/bin/autopkgtest ]; then
  # new autopkgtest interface
  set -x
  sudo DEB_PG_SUPPORTED_VERSIONS="$DEB_PG_SUPPORTED_VERSIONS" \
    autopkgtest --summary $ADT_SUMMARY \
	$SBUILD_PKGBUILD_DIR/ \
	$SBUILD_BUILD_DIR/*.deb \
	-- null
else
  # old adt interface
set -x
sudo DEB_PG_SUPPORTED_VERSIONS="$DEB_PG_SUPPORTED_VERSIONS" LC_ALL=C.UTF-8 \
  adt-run --summary $ADT_SUMMARY \
	$SBUILD_BUILD_DIR/*.deb \
	--built-tree $SBUILD_PKGBUILD_DIR \
	--- adt-virt-null
fi
) || EXIT=$?

case ${EXIT:-0} in
  0|2|4|6) # 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
    ;;
  8) # "SKIP no tests in this package"
    adtsummary2junit /dev/null > $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
