#!/usr/bin/env bash
set -e

function yes_or_no {
	while true; do
		read -p "$* [y/n]: " yn
		case $yn in
		[Yy]*) return 0 ;;
		[Nn]*)
			echo "Aborted"
			return 1
			;;
		esac
	done
}

myDir=$(dirname "$0")
scriptsDir=$(dirname "$myDir")
CUR_VERSION=$($scriptsDir/version-core)

MAJOR_FLAG=
VERSION=
while [[ $# -gt 0 ]]; do
	case $1 in
	--major) MAJOR_FLAG=1; shift ;;
	-*) echo "Unknown option: $1"; exit 1 ;;
	*) VERSION=$1; shift ;;
	esac
done

if [ -z "$VERSION" ]; then
	echo "Usage: $0 [--major] VERSION"
	echo "Current version: $CUR_VERSION"
	exit 1
fi

set -x

$scriptsDir/check-python-version

VALIDATE_ARGS=()
[ -n "$MAJOR_FLAG" ] && VALIDATE_ARGS+=(--major)
python3 "$myDir/validate-release-tag.py" "${VALIDATE_ARGS[@]}" "$VERSION"

$scriptsDir/version-set.py $VERSION

sudo rm -rf dist build
mkdir dist build
python3 setup.py sdist bdist_wheel
pip3 install ./dist/*.whl -U --user --force-reinstall
du -k dist/*

echo "-------------- Check version in GUI: --------------"

~/.local/bin/pyglossary

yes_or_no "Continue creating the release?" || exit 1

git add setup.py pyglossary/core.py pyproject.toml about _license-dialog
git commit -m "version $VERSION" || echo "------ Already committed"
git -p show || true
git -p log || true

echo "Pushing to origin..."
git push

echo "Creating tag $VERSION"
git tag -a -m "version $VERSION" $VERSION

echo "Pushing tag to origin..."
git push origin $VERSION

echo "Publishing to pypi"
python3 -m twine upload --repository pypi dist/* --verbose
