#!/bin/sh

set -e

# Test that with a stestr 3.x (which answers the run --help probe
# without the stestr >= 4 flag names), the selection lists are passed
# with the legacy flag names --blacklist-file and --whitelist-file,
# which have the same file format.

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

# The mock answers the "run --help" probe the way stestr 3.x does,
# and only logs the real invocations.
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 -- "--blacklist-file --whitelist-file\\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

cd "${WORK}"
printf '[DEFAULT]\ntest_path = ./tests\n' >.stestr.conf
mkdir -p debian/tests
printf 'some\\.excluded\\.test\\..*\n' >debian/tests/exclude-list.txt
printf 'some\\.included\\.test\\..*\n' >debian/tests/include-list.txt
"${SCRIPT}" >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_BLACKLIST="--blacklist-file ${WORK}/debian/tests/exclude-list.txt"
case "${RUN_LINE}" in
*"${WANT_BLACKLIST}"*) ;;
*)
	echo "${ME}: stestr wasn't called with --blacklist-file: ${RUN_LINE}"
	exit 1
	;;
esac

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

case "${RUN_LINE}" in
*--exclude-list*|*--include-list*)
	echo "${ME}: stestr got the stestr >= 4 flag names: ${RUN_LINE}"
	exit 1
	;;
esac

exit 0
