#!/bin/sh

set -e

# Test that debian/tests/exclude-list.txt and
# debian/tests/include-list.txt are passed to stestr with the
# stestr >= 4 flags (--exclude-list and --include-list, as announced
# by the mocked run --help), and that command line regexes are still
# forwarded verbatim.

ME=$(basename $0)
WORK=$(mktemp -d)
trap 'rm -rf "${WORK}"' EXIT

# Mock py3versions with a python4 version, so that the check for
# /usr/bin/python4-stestr fails, and the script falls back to the
# stestr from the PATH, which is mocked below. The mock answers the
# "run --help" probe of pkgos-dh_auto_test with the stestr >= 4 flag
# names, without logging it, so that only real invocations land in
# the log.
mkdir -p "${WORK}/bin"
printf '#!/bin/sh\necho 4.2\n' >"${WORK}/bin/py3versions"
printf '#!/bin/sh\ncat >/dev/null\n' >"${WORK}/bin/subunit2pyunit"
printf '#!/bin/sh\nif [ "${2}" = "--help" ] ; then printf -- "--exclude-list --include-list\\n" ; exit 0 ; fi\necho "$@" >>"${STESTR_MOCK_LOG}"\n' >"${WORK}/bin/stestr"
chmod +x "${WORK}/bin/py3versions" "${WORK}/bin/subunit2pyunit" "${WORK}/bin/stestr"

PATH="${WORK}/bin:${PATH}"
export PATH
STESTR_MOCK_LOG="${WORK}/stestr.log"
export STESTR_MOCK_LOG

SCRIPT=$(cd "$(dirname "$0")/../../../build-tools" && pwd)/pkgos-dh_auto_test

# Run the script in a safe temp dir holding a .stestr.conf and the
# two selection files, so that it takes the stestr branch and picks
# the selection lists up.
cd "${WORK}"
printf '[DEFAULT]\ntest_path = ./tests\n' >.stestr.conf
mkdir -p debian/tests
printf '# Needs SQL connectivity\nsome\\.excluded\\.test\\..*\n' >debian/tests/exclude-list.txt
printf 'some\\.included\\.test\\..*\n' >debian/tests/include-list.txt
"${SCRIPT}" 'cmdline_regex' >out.log 2>&1 || {
	cat out.log
	echo "${ME}: pkgos-dh_auto_test failed"
	exit 1
}

RUN_LINE=$(grep '^run' "${STESTR_MOCK_LOG}" || true)
if [ -z "${RUN_LINE}" ] ; then
	echo "${ME}: the stestr mock never saw a run command"
	exit 1
fi

WANT_EXCLUDE="--exclude-list ${WORK}/debian/tests/exclude-list.txt"
case "${RUN_LINE}" in
*"${WANT_EXCLUDE}"*) ;;
*)
	echo "${ME}: stestr wasn't called with --exclude-list: ${RUN_LINE}"
	exit 1
	;;
esac

WANT_INCLUDE="--include-list ${WORK}/debian/tests/include-list.txt"
case "${RUN_LINE}" in
*"${WANT_INCLUDE}"*) ;;
*)
	echo "${ME}: stestr wasn't called with --include-list: ${RUN_LINE}"
	exit 1
	;;
esac

case "${RUN_LINE}" in
*cmdline_regex*) ;;
*)
	echo "${ME}: the command line regex wasn't forwarded: ${RUN_LINE}"
	exit 1
	;;
esac

case "${RUN_LINE}" in
*--blacklist-file*|*--whitelist-file*)
	echo "${ME}: stestr got the legacy stestr 3 flag names: ${RUN_LINE}"
	exit 1
	;;
esac

exit 0
