#!/bin/sh

set -e

EXCLUDE_FILE=/etc/tempest/exclude.conf
TMP_EXCLUDE=`mktemp -t nose-exclude-XXXXXX`
if [ -r "${EXCLUDE_FILE}" ] ; then
	for i in `grep -v -e '^#' -e '^[ \t]*$' ${EXCLUDE_FILE}` ; do
		if [ -n "${A}" ] ; then
			A="${A}|${i}"
		else
			A="${i}"
		fi
	done
fi

cd /var/lib/tempest

if [ ! -d .stestr ] ; then
	PYTHON=python3 stestr init
fi

# Use stestr's experimental dynamic scheduler when the installed stestr
# supports it: workers pull test ids from a shared queue so they stay
# busy until every test has been handed out, instead of the static
# pre-partitioning of the default --parallel mode.
if stestr run --help | grep -q dynamic ; then
	MODE="--dynamic --dynamic-progress"
else
	MODE=--parallel
fi

if [ "${MODE}" = "--parallel" ] ; then
	# The classic static scheduler renders through subunit-trace, like
	# it always did.
	if [ -z "${1}" ] && [ -n ${A} ] ; then
		PYTHON=python3 stestr run ${MODE} --concurrency=$(nproc) --subunit '^(?!('"${A}"'))' $@ | subunit-trace
	else
		PYTHON=python3 stestr run ${MODE} --concurrency=$(nproc) --subunit $@ | subunit-trace
	fi
else
	# In dynamic mode, let stestr render the output itself: its pretty
	# output is rendered by its internal copy of subunit-trace, with
	# the same per-test lines and durations, and the Totals, the
	# Worker Balance and the failure details. Piping the raw subunit
	# stream through subunit-trace would be redundant with that, and
	# the per-test progress reporter of that path is the youngest and
	# least tested piece of the dynamic scheduler: it is what aborted
	# a whole run when its first completed test was a setUpClass skip
	# (the ETA was computed from a never-seeded elapsed time,
	# stestr 4.2.1-11).
	if [ -z "${1}" ] && [ -n ${A} ] ; then
		PYTHON=python3 stestr run ${MODE} --concurrency=$(nproc) '^(?!('"${A}"'))' $@
	else
		PYTHON=python3 stestr run ${MODE} --concurrency=$(nproc) $@
	fi
fi

#testr run --parallel --subunit $@ | subunit-trace
