#!/bin/sh

set -e
set -x

PKGOS_USE_PY2=yes
PKGOS_USE_PY3=yes
PYTHONS=disabled
PYTHON3S=disabled

for i in $@ ; do
	case "${1}" in
	"--no-py3")
		PKGOS_USE_PY3=no
		shift
		;;
	"--no-py2")
		PKGOS_USE_PY2=no
		shift
		;;
	*)
		;;
	esac
done

if [ "${PKGOS_USE_PY2}" = "yes" ] ; then
	PYTHONS=2.7
fi
if [ "${PKGOS_USE_PY3}" = "yes" ] ; then
	PYTHON3S=$(py3versions -vr 2>/dev/null)
fi

for pyvers in ${PYTHONS} ${PYTHON3S}; do
	if [ "${pyvers}" = "disabled" ] ; then
		continue
	fi
	PYMAJOR=$(echo ${pyvers} | cut -d'.' -f1)
	echo "===> Testing with python${pyers} (python${PYMAJOR})"
	if [ -e .stestr.conf ] ; then
		rm -rf .stestr
		python${PYMAJOR}-stestr init
		TEMP_REZ=$(mktemp -t)
		PYTHONPATH=$(pwd) PYTHON=python${pyvers} python${PYMAJOR}-stestr run --subunit ${1} | tee ${TEMP_REZ} | subunit2pyunit
		cat ${TEMP_REZ} | subunit-filter -s --no-passthrough | subunit-stats
		rm -f ${TEMP_REZ}
		python${PYMAJOR}-stestr slowest
		rm -rf .stestr
	elif [ -e .testr.conf ] ; then
		rm -rf .testrepository
		testr-python${PYMAJOR} init
		TEMP_REZ=$(mktemp -t)
		PYTHONPATH=$(pwd) PYTHON=python${pyvers} testr-python${PYMAJOR} run --subunit ${1} | tee ${TEMP_REZ} | subunit2pyunit
		cat ${TEMP_REZ} | subunit-filter -s --no-passthrough | subunit-stats
		rm -f ${TEMP_REZ}
		testr-python${PYMAJOR} slowest
		rm -rf .testrepository
	fi
done
