#!/usr/bin/env sh

red=${NO_COLOR:-$(tput setaf 1)}
grn=${NO_COLOR:-$(tput setaf 2)}
clr=${NO_COLOR:-$(tput sgr0)}
p=$(which poetry)
prun="${p} run"

if ! [ "$p" ]; then
    echo "${red}WARNING:${clr} Poetry is not in your PATH! It is required as our
	dependency manager. Please install it (https://python-poetry.org)."
    exit 1
fi

ci() {
	fail() { printf "\n\n=== %s%s FAILED!%s ===" "${red}" "$1" "${clr}"; exit 2; }
	lint() { ($prun flake8 proselint tests && $prun pydocstyle proselint tests) || fail "LINT"; }
	unittest() {
		pytest="pytest --continue-on-collection-errors"
		if [ "$1" = "-c" ] || [ "$1" = "--coverage" ]; then
			$prun coverage run -m $pytest || fail;
			$prun coverage xml
		else
			$prun $pytest || fail;
		fi
	}
	case $1 in
		lint) lint;;
		test) unittest "$2";;
		*) lint && unittest "${2:-$1}";;
	esac

	printf "\n\n%sSuccess!%s Your PR is ready to submit." "${grn}" "${clr}"
}

case $1 in
	build) $p build;;
	ci) ci "$2" "$3";;
	publish)
		DIST="${2:-./dist/*}"
		echo "- Uploading distribution from ${DIST}"
		$prun twine upload $DIST
		echo "- ${grn}Upload complete.${clr}"
		;;
	version)
		VERSION="${2:-patch}"
		echo "${red}WARNING:${clr} This assumes you have updated CHANGELOG.md.
		Please remember to do so prior to running this command."
		git stash
		echo "- Updating version in ${grn}${VERSION}${clr} mode."
		$prun bumpversion "${VERSION}"
		echo "- Appending CHANGELOG.md."
		git stash pop
		git add CHANGELOG.md
		git commit --amend --no-edit
		NEWVERSION=$(python -m proselint --version)
		echo "- Retagging ${NEWVERSION}."
		git tag --delete "${NEWVERSION}" && git tag "${NEWVERSION}"
		echo "- ${grn}Versioning complete.${clr}"
		;;
	*)
		echo "
Usage:
  $0 build
  $0 ci [lint|test] [-c|--coverage]
  $0 publish <dist directory>
  $0 version <bumpversion mode>"
		exit 1
		;;
esac
