#!/bin/sh

# . "$(dirname "$0")"/functions.sh

if [ $# -ge 1 ]; then
  # optionally allow tagging from a specified branch rather than master/main
  check_branch="$1"
  shift
fi

if [ -n "${check_branch}" ] && ! branch_is "${check_branch}"; then
  _cur_branch="$(git_current_branch)"
  quit "Attempting to tag from branch ${_cur_branch}, not ${check_branch}. Check out ${check_branch} first." 1
fi

if [ -z "${check_branch}" ] && ! branch_is_master_or_main; then
  _cur_branch="$(git_current_branch)"
  quit "Attempting to tag from branch ${_cur_branch}. Check out 'main' or 'master' first." 1
fi

if ! branch_is_clean; then
  echo "Tree contains uncommitted modifications:"
  git ls-files -m
  quit 1
fi

version=$(current_version) || quit $?

if version_is_tagged "${version}"; then
  echo "Version ${version} already tagged."
  git --no-pager tag -l
  quit 0
fi

echo "Tagging version: ${version}"

# normally git tag -a is implied if we specify -m
# if tag.forceSignAnnotated = true, then -s is implied instead
git tag "v${version}" -m "version ${version}" || quit "Failed to tag ${version}" $?

echo "Tags:"
git --no-pager tag -l

quit "Done." 0
