#!/bin/sh

set -e
set -x

# Config vars
PKGOS_TEST_PARALLEL=yes
PKGOS_TEST_SERIAL=no
PKGOS_TEST_DYNAMIC=no

# Vars used in commands
PYTHONS=disabled
PYTHON3S=disabled
TEST_PARALLEL_OPT="--parallel"
TEST_SERIAL_OPT=""

# Data driven test selection: if present in the package source tree,
# these two files hold the regexes of the tests to include and
# exclude, using stestr's own list file format: one regex per line,
# and anything after a # on a line is a comment (which stestr
# displays as the reason why a test was skipped). The include regexes
# are OR'ed with the command line regexes, and the excluded tests are
# removed from the selection afterwards.
TEST_INCLUDE_LIST=`pwd`/debian/tests/include-list.txt
TEST_EXCLUDE_LIST=`pwd`/debian/tests/exclude-list.txt

# Extracts the regexes of one selection file: strip the comments,
# trim, and drop the empty lines. This mirrors what stestr's own
# exclusion_reader does when it reads the file by itself.
read_test_list () {
	sed -e 's/#.*$//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' "${1}"
}

# Joins the regexes of one selection file with |, which is needed for
# testrepository: it cannot read the selection files by itself, so a
# combined regex must be built for it. Outputs nothing if the file
# doesn't exist or holds no regex.
join_test_list () {
	if [ -e "${1}" ] ; then
		read_test_list "${1}" | tr '\n' '|' | sed -e 's/|$//'
	fi
}

for i in $@ ; do
	case "${1}" in
	"--no-py3")
		echo "WARNING: --no-py3 is deprecated, and always off."
		shift
		;;
	"--no-py2")
		echo "WARNING: --no-py2 is deprecated, and always on."
		shift
		;;
	"--no-parallel")
		PKGOS_TEST_PARALLEL=no
		shift
		;;
	"--serial")
		PKGOS_TEST_SERIAL=yes
		PKGOS_TEST_PARALLEL=no
		PKGOS_TEST_DYNAMIC=no
		shift
		;;
	"--dynamic")
		PKGOS_TEST_PARALLEL=no
		PKGOS_TEST_SERIAL=no
		PKGOS_TEST_DYNAMIC=yes
		shift
		;;
	*)
		;;
	esac
done

PYTHON3S=$(py3versions -vr 2>/dev/null)
if [ "${PKGOS_TEST_PARALLEL}" = "no" ] ; then
	TEST_PARALLEL_OPT=""
fi
if [ "${PKGOS_TEST_SERIAL}" = "yes" ] ; then
	TEST_SERIAL_OPT="--serial"
fi
if [ "${PKGOS_TEST_DYNAMIC}" = "yes" ] ; then
	TEST_PARALLEL_OPT="--dynamic"
fi

for pyvers in ${PYTHON3S}; do
	if [ "${pyvers}" = "disabled" ] ; then
		continue
	fi
	PYMAJOR=$(echo ${pyvers} | cut -d'.' -f1)
	echo "===> Testing with python${pyvers} (python${PYMAJOR})"
	if [ -d `pwd`/debian/tmp/usr/lib/python3/dist-packages ] && [ -z "${PYTHONPATH}" ] ; then
		echo "Implicitly adding PYTHONPATH="`pwd`"/debian/tmp/usr/lib/python3/dist-packages"
		export PYTHONPATH=`pwd`/debian/tmp/usr/lib/python3/dist-packages
	fi
	if [ -e .stestr.conf ] ; then
		if [ -x /usr/bin/python${PYMAJOR}-stestr ] ; then
			STESTR=/usr/bin/python${PYMAJOR}-stestr
		else
			STESTR=stestr
		fi
		# stestr 4 renamed the options holding the selection
		# lists, without changing their file format: probe the
		# option names through the help output of the stestr
		# that is about to be used.
		TEST_LISTS_OPTS=""
		if [ -e "${TEST_EXCLUDE_LIST}" ] || [ -e "${TEST_INCLUDE_LIST}" ] ; then
			if ${STESTR} run --help 2>&1 | grep -q -- --exclude-list ; then
				EXCLUDE_LIST_OPT="--exclude-list"
				INCLUDE_LIST_OPT="--include-list"
			else
				EXCLUDE_LIST_OPT="--blacklist-file"
				INCLUDE_LIST_OPT="--whitelist-file"
			fi
			if [ -e "${TEST_EXCLUDE_LIST}" ] ; then
				TEST_LISTS_OPTS="${TEST_LISTS_OPTS} ${EXCLUDE_LIST_OPT} ${TEST_EXCLUDE_LIST}"
			fi
			if [ -e "${TEST_INCLUDE_LIST}" ] ; then
				TEST_LISTS_OPTS="${TEST_LISTS_OPTS} ${INCLUDE_LIST_OPT} ${TEST_INCLUDE_LIST}"
			fi
		fi
		rm -rf .stestr
		if [ "${PKGOS_TEST_DYNAMIC}" = "yes" ] ; then
			# The dynamic mode renders the per-test progress
			# ([ n/m (p%) ETA: ~t] test.path [t] ... ok) itself:
			# feeding a raw stream to subunit2pyunit would make
			# its stdout interleave with the progress stestr
			# writes to stderr, mangling the build log. stestr
			# exits 1 on failing tests, so the error handling is
			# the same as with the pipeline below.
			if ! PYTHON=python${pyvers} ${STESTR} run --dynamic --dynamic-progress ${TEST_LISTS_OPTS} $@ ; then
				echo "======> STESTR TEST SUITE FAILED FOR python${pyvers}: displaying pip3 freeze output..."
				if [ -x /usr/bin/pip3 ] ; then
					pip3 freeze
				fi
				exit 1
			fi
		else
			if ! PYTHON=python${pyvers} ${STESTR} run ${TEST_SERIAL_OPT} ${TEST_PARALLEL_OPT} ${TEST_LISTS_OPTS} --subunit $@ | subunit2pyunit ; then
				echo "======> STESTR TEST SUITE FAILED FOR python${pyvers}: displaying pip3 freeze output..."
				if [ -x /usr/bin/pip3 ] ; then
					pip3 freeze
				fi
				exit 1
			fi
		fi
		${STESTR} slowest
		rm -rf .stestr
	elif [ -e .testr.conf ] ; then
		if [ -x /usr/bin/testr-python${PYMAJOR} ] ; then
			TESTR=/usr/bin/testr-python${PYMAJOR}
		else
			TESTR=testr
		fi
		if [ "${PKGOS_TEST_DYNAMIC}" = "yes" ] ; then
			echo "ERROR: testrepository doesn't support --dynamic." >&2
			exit 1
		fi
		rm -rf .testrepository
		${TESTR} init
		TEMP_REZ=$(mktemp -t)
		# testrepository cannot read the selection files by
		# itself: build one combined regex out of the command
		# line regexes and the selection lists, with the same
		# semantics as what stestr does with the files (the
		# inclusions are OR'ed, then the excluded tests are
		# removed from anywhere in the test ids).
		TESTR_INCLUDES="$(join_test_list "${TEST_INCLUDE_LIST}")"
		TESTR_EXCLUDES="$(join_test_list "${TEST_EXCLUDE_LIST}")"
		if [ -n "${TESTR_EXCLUDES}" ] ; then
			TESTR_ALL_INCLUDES="$*"
			if [ -n "${TESTR_ALL_INCLUDES}" ] && [ -n "${TESTR_INCLUDES}" ] ; then
				TESTR_ALL_INCLUDES="${TESTR_ALL_INCLUDES}|${TESTR_INCLUDES}"
			elif [ -z "${TESTR_ALL_INCLUDES}" ] ; then
				TESTR_ALL_INCLUDES="${TESTR_INCLUDES}"
			fi
			if [ -n "${TESTR_ALL_INCLUDES}" ] ; then
				TESTR_RUN_ARGS="(${TESTR_ALL_INCLUDES})(?!.*(?:${TESTR_EXCLUDES}))"
			else
				TESTR_RUN_ARGS="^(?!.*(?:${TESTR_EXCLUDES}))"
			fi
		elif [ -n "${TESTR_INCLUDES}" ] ; then
			TESTR_RUN_ARGS="$* (${TESTR_INCLUDES})"
		else
			TESTR_RUN_ARGS="$*"
		fi
		if ! PYTHON=python${pyvers} ${TESTR} run ${TEST_SERIAL_OPT} ${TEST_PARALLEL_OPT} --subunit ${TESTR_RUN_ARGS} | tee ${TEMP_REZ} | subunit2pyunit ; then
			echo "======> TESTR TEST SUITE FAILED FOR python${pyvers}: displaying pip3 freeze output..."
			if [ -x /usr/bin/pip3 ] ; then
				pip3 freeze
			fi
			exit 1
		fi
		cat ${TEMP_REZ} | subunit-filter -s --no-passthrough | subunit-stats
		rm -f ${TEMP_REZ}
		${TESTR} slowest
		rm -rf .testrepository
	fi
done
