#!/bin/sh

set -eu

if [ $# -lt 1 ]; then
  echo "usage: $0 [AUTOPKGTEST ARGUMENTS ...]"
  exit 1
fi

# Merge $@ and $debci_autopkgtest_args, because the latter contain nested
# strings that break with simple expansion, eg:
#
#    debci_autopkgtest_args="--setup-commands='mycmd arg1 arg2'"
#
# $@ already contains the virtualization backend parameters so we cannot
# append; instead, we prepend in reverse
if [ -n "${debci_autopkgtest_args:-}" ]; then
  while read -r arg; do
    set -- "$arg" "$@"
  done <<EOF
$(printf '%s\n' "${debci_autopkgtest_args:-}" | xargs printf '%s\n' | tac)
EOF
fi

rc=0
# shellcheck disable=SC2154,SC2086
autopkgtest \
  --no-built-binaries \
  --setup-commands="echo '${debci_test_package} ${debci_suite}/${debci_arch}' > /var/tmp/debci.pkg 2>&1 || true" \
  --setup-commands="echo 'Acquire::Retries \"10\";' > /etc/apt/apt.conf.d/75retry 2>&1 || true" \
  "$@" || rc=$?

if [ -n "${debci_test_outputdir:-}" ] && [ -d "${debci_test_outputdir}" ]; then
  echo $rc > "$debci_test_outputdir/exitcode"
  hostname -s > "$debci_test_outputdir/worker"
fi
exit $rc
