#!/bin/bash
set -eux
# By default, run tests with pytest-forked plugin,
# disable in terminal for debugging, you may add --forked
flag_forked="--forked"
if [[ -z "${CI:-}" ]] && [[ -t 1 ]] ; then
	flag_forked=""
fi
test_flags=(
	$@
	$flag_forked
	tests/
)

main() {
	cd "$( dirname "${BASH_SOURCE[0]}" )/.."
	if [[ -n "${CI:-}" ]] ; then
		case "${test_group-}" in
		package)
			# TODO: sdist bdist_wheel
			# but wheels don't roll well with our 2/3 split code base
			python setup.py sdist
			install_check_version "pip"
			;;
		*)
			pip install -e .
			httplib2_test_still_run_skipped=1 pytest --fulltrace -k test_303 $@ tests/ || true
			httplib2_test_still_run_skipped=1 pytest --fulltrace -k test_head_301 $@ tests/ || true
			pytest --fulltrace ${test_flags[@]}
			;;
		esac
	else
		if [[ ! -d ./venv-27 ]] ; then
			virtualenv --python=python2.7 ./venv-27
		fi
		if [[ ! -d ./venv-36 ]] ; then
			virtualenv --python=python3.6 ./venv-36
		fi

		./venv-27/bin/pip install -e . -r requirements-test.txt
		./venv-27/bin/pytest ${test_flags[@]}
		./venv-36/bin/pip install -e . -r requirements-test.txt
		./venv-36/bin/pytest ${test_flags[@]}

		# FIXME: too many errors
		# ./venv-27/bin/flake8 python2/
		# ./venv-36/bin/flake8 python3/ tests/

		# TODO: sdist bdist_wheel
		# but wheels don't roll well with our 2/3 split code base
		./venv-36/bin/python setup.py sdist
		install_check_version "./venv-27/bin/pip"
		install_check_version "./venv-36/bin/pip"
	fi
	rm -rf ./_httplib2_test_cache
}

install_check_version() {
	local pip="$1"
	$pip install dist/httplib2*
	version_source=$(python setup.py --version)
	version_installed=$($pip show httplib2 |fgrep Version: |cut -d' ' -f2)
	if [[ "$version_source" != "$version_installed" ]] ; then
		echo "error: installed package version=$version_installed does not match source=$version_source" >&2
		exit 1
	fi
}

main "$@"
