#!/bin/bash
set -e

pkg=q2_types

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

cp -a /usr/lib/python3/dist-packages/${pkg}* "${AUTOPKGTEST_TMP}"

cd "${AUTOPKGTEST_TMP}"

if [ ! -f /usr/lib/python3/dist-packages/pytest_cov/__init__.py ] ; then
	echo "Please install package python3-pytest-cov to run this script"
	exit 1
fi

# Run build-time tests
# for py in $(py3versions -s 2> /dev/null) # FIXME: qiime 3.12 issue reported in https://github.com/qiime2/qiime2/issues/751
for py in $(py3versions -d 2> /dev/null)
do
    # Test modules that import a python module not yet packaged in Debian
    # would abort the whole run at collection time.  Ignore just those.
    # Each failing module is probed in a fresh interpreter, since imports
    # left behind by an earlier module can mask the missing one.  Any
    # other import failure is left to pytest, so genuine bugs still fail.
    ignores=()
    while : ; do
        new=0
        errs=$(${py} -m pytest --collect-only -q "${ignores[@]}" 2>&1 || true)
        for f in $(sed -n 's/^ERROR \(q2_types\/.*\.py\).*/\1/p' \
                   <<<"${errs}" | sort -u); do
            mod=${f%.py}
            mod=${mod//\//.}
            out=$(${py} -c "import ${mod}" 2>&1 || true)
            miss=$(sed -n "s/.*No module named '\([^']*\)'.*/\1/p" \
                   <<<"${out}" | tail -1)
            if [ -n "${miss}" ] && [[ ${miss} != ${pkg}* ]] ; then
                echo "Ignoring ${f}: ${miss} not packaged in Debian"
                ignores+=(--ignore="${f}")
                new=1
            fi
        done
        [ ${new} = 1 ] || break
    done

    ${py} -m pytest -v --cov=${pkg} "${ignores[@]}"
done
