#!/bin/sh

set -e

# Test that without any option, stestr is called with --parallel.

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.
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\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, so that it
# takes the stestr branch.
cd "${WORK}"
printf '[DEFAULT]\ntest_path = ./tests\n' >.stestr.conf
"${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
case "${RUN_LINE}" in
*--parallel*) ;;
*)
	echo "${ME}: stestr wasn't called with --parallel: ${RUN_LINE}"
	exit 1
	;;
esac
case "${RUN_LINE}" in
*--dynamic*|*--serial*)
	echo "${ME}: stestr got a wrong option: ${RUN_LINE}"
	exit 1
	;;
esac

exit 0
