#!/bin/bash
set -e

echo "Fetching any updates from server:"
git pull
echo ""

cur_branch=$(git branch --show-current)

if [[ -z ${1} ]]; then
	deftag="${cur_branch}"
else
	deftag="${1}"
fi

if ! [[ ${deftag} =~ ${cur_branch} ]] && ! [[ ${GIT_PUSH_EXTRA} =~ '--no-verify' ]]; then
	echo "Your tag: ${deftag} does not match the name of the branch: ${cur_branch}."
	echo "To push anyway, run: GIT_PUSH_EXTRA='--no-verify' ${0} ${*}"
	exit 1
fi

tagpfx=${tag:="${deftag}"}

if [[ -z ${ALLOW_NEW_TAG} ]]; then
	echo "${0}: Looking for last-tag matching ${tagpfx}-2*"
	last_tag=$(git tag -l "${tagpfx}-2*" | sort | tail -1)

	if [[ -z ${last_tag} ]]; then
		echo ""
		echo -e "Tag matching \e[1m${tagpfx}-2* NOT FOUND\e[0m, aborting."
		echo "To create new tag, run: ALLOW_NEW_TAG=true ${0} ${*}"
		exit 1
	fi

	echo -e "Verifying last tag \e[94m${last_tag}\e[0m:"
	(git tag -v "${last_tag}" 2>&1 | grep ^gpg:) || true
	# again to not mask exit status of git with grep
	git tag -v "${last_tag}" >/dev/null 2>&1
	echo ""
	echo "Differences between tag ${last_tag} and what you are about to sign:"
	git log --pretty=format:'%h %an %G? %s' --graph "${last_tag}..HEAD"

	echo "Press enter to see diff"
	read -r

	PAGER="cat" git diff --color "${last_tag}"..HEAD
	iter=1
	ok=

	while test -z "${ok}"; do
		this_tag=$(date "+${tagpfx}-%Y-%m-%d-v$(printf "%02d" ${iter})")
		iter=$((iter + 1))
		case $( (
			echo "${this_tag}"
			echo "${last_tag}"
		) | sort | tail -1) in
		"${last_tag}") ;;
		"${this_tag}")
			ok=yes
			;;
		esac
	done
	extra_message=" AND DIFF ABOVE"
else
  this_tag=$(date "+${tagpfx}-%Y-%m-%d-v1")
fi

echo ""
echo -e "Using new tag \e[94m${this_tag}\e[0m"
echo -e "\e[1mONLY SIGN IF YOU APPROVE OF VERIFICATION${extra_message}\e[0m"

# GIT_TAG_EXTRA is for putting things like "-u 2117364A"
# shellcheck disable=SC2086
git tag ${GIT_TAG_EXTRA} -m bump. -s "${this_tag}"

# GIT_PUSH_EXTRA is for putting things like "--no-verify"
# shellcheck disable=SC2086
git push ${GIT_PUSH_EXTRA}

# shellcheck disable=SC2086
git push --tags ${GIT_PUSH_EXTRA}