#!/bin/sh

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

# Input:
#  %SBUILD_BUILD_DIR %SBUILD_PKGBUILD_DIR
#  DEB_ADT_SUMMARY (required)
#  PG_SUPPORTED_VERSIONS (required)
# Output:
#  autopkgtest test results in DEB_ADT_SUMMARY

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

(
  set -x
  sudo PG_SUPPORTED_VERSIONS="$PG_SUPPORTED_VERSIONS" \
    autopkgtest --summary $DEB_ADT_SUMMARY \
	--timeout-copy=900 \
	$SBUILD_PKGBUILD_DIR/ \
	$SBUILD_BUILD_DIR/*.deb \
	-- null
) || EXIT=$?

echo "autopkgtest exit status is ${EXIT:=0}"
case $EXIT in
  0|2|4|6|8) # all ok or some test failed/was skipped, exit 0 here and let adtsummary2junit report the failure to jenkins
    exit 0
    ;;
  *) # in reality, sbuild ignores failures here, but jenkins will complain if the junit xml result file is empty
    exit $EXIT
    ;;
esac

