#!/bin/bash
set -eu
cd "$( dirname "${BASH_SOURCE[0]}" )/.."

version=
version_next=

main() {
	local branch="${1-$(git symbolic-ref --short HEAD)}"
	version="$(PYTHONPATH=$PWD/python2 python2 -c 'import httplib2; print(httplib2.__version__)')"
	printf "\nbranch: %s httplib2.__version__: '%s'\n" $branch $version >&2

	if [[ "$branch" != "master" ]]; then
		echo "Must be on master" >&2
		exit 1
	fi
	if [[ -n "$(git status --short -uall)" ]]; then
		echo "Tree must be clean. git status:" >&2
		echo "" >&2
		git status --short -uall
		echo "" >&2
		exit 1
	fi
	confirm "Continue? [yN] " || exit 1

	echo "Creating tag v$version" >&2
	if ! git tag "v$version"; then
		echo "git tag failed " >&2
		confirm "Continue still? [yN] " || exit 1
	fi

    echo "Building package" >&2
    find . -name '*.pyc' -o -name '*.pyo' -o -name '*.orig' -delete
    rm -rf python{2,3}/.cache
    rm -rf build dist
    # TODO: sdist bdist_wheel
    # but wheels don't roll well with our 2/3 split code base
    local venv=./venv-release
    if [[ ! -d "$venv" ]] ; then
        virtualenv $venv
        $venv/bin/pip install -U pip setuptools wheel twine
    fi
    $venv/bin/python setup.py sdist

	if confirm "Upload to PyPi? [Yn] "; then
		$venv/bin/twine upload dist/* || exit 1
	fi

	git push --tags
}

confirm() {
	local reply
	local prompt="$1"
	read -n1 -p "$prompt" reply >&2
	echo "" >&2
	rc=0
	local default_y=" \[Yn\] $"
	if [[ -z "$reply" ]] && [[ "$prompt" =~ $default_y ]]; then
		reply="y"
	fi
	[[ "$reply" != "y" ]] && rc=1
	return $rc
}

main "$@"
