#!/bin/sh

set -e

# Test that a debian/tests/include-list.txt alone is passed to stestr
# with --include-list, and that the command line regexes are still
# forwarded verbatim next to it (stestr ORs them with the include
# list entries).

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

# The mock answers the "run --help" probe with the stestr >= 4 flag
# names, 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 -- "--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

cd "${WORK}"
printf '[DEFAULT]\ntest_path = ./tests\n' >.stestr.conf
mkdir -p debian/tests
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_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
*--exclude-list*|*--blacklist-file*|*--whitelist-file*)
	echo "${ME}: stestr got an exclusion flag without an exclude list: ${RUN_LINE}"
	exit 1
	;;
esac

exit 0
