#!/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/
)
if [[ -n "${CI:-}" ]] ; then
	test_flags+=(--fulltrace)
fi
: "${stages="venv,style,test,check_version"}"

main() {
	cd "$( dirname "${BASH_SOURCE[0]}" )/.."
	if enabled venv && [[ -z "${CI:-}${VIRTUAL_ENV:-}" ]] ; then
		echo "environment: neither CI nor existing virtualenv, using \`python -m venv ./venv\`" >&2
		[[ -x venv/bin/pip ]] || python -m venv venv
		source venv/bin/activate
	fi

	if enabled style ; then
		pip install black isort -r requirements-test.txt
		# TODO enable after initial black/isort run
        # isort httplib2/ tests/
        # black httplib2/ tests/
        flake8 httplib2/ tests/
	fi

	if enabled test ; then
		pip install -e . -r requirements-test.txt
		pytest --fulltrace "${test_flags[@]}"
	fi

	if enabled check_version ; then
        rm -f dist/*.gz
        pip install setuptools
		python setup.py sdist bdist_wheel
		install_check_version
	fi

	rm -rf ./_httplib2_test_cache
}

enabled() {
	[[ ",${stages}," = *,$1,* ]] || return 1
}

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

main "$@"
