#!/bin/sh
#
# Create a git tag for main and sub-repos and push to remote.
#
# Usage:
#   $ cd path/to/lrauv-application
#   $ ./Tools/gittag.sh <deployment name>
#
# LRAUV deployment name is of the format: <vehicle name> <deployment num> <deployment objective> (e.g., 'Tethys 77 MBTS')
#
# To undo/remove a tag:
#   git tag -d <tag name>;               # rm tag from local
#   git push --delete origin <tag name>; # rm tag from remote
#   git submodule foreach --recursive "(git tag -d <tag name>;git push --delete origin <tag name>)&" # rm tag from submodules
#

if [ $# -eq 1 ]; then
  DEPLOYMENT=$1
else
  echo ""
  echo "A deployment name is required for tag message."
  echo ""
  echo "      usage example: ./Tools/`basename $0` 'Tethys 77 MBTS'"
  echo ""
  exit
fi

TAGNAME=$(date -u +%F)
MSG="tag for $DEPLOYMENT"
bold=$(tput bold)
normal=$(tput sgr0)

# Check if the auto-generated tag name already exists in the repo
echo ""
git fetch --tags &> /dev/null
if git ls-remote --exit-code origin refs/tags/$TAGNAME; then
  echo "Tag ${bold}$TAGNAME${normal} already exists in remote!"
  echo "Enter tag name for $DEPLOYMENT: " && read response

  if [ -z "$response" ]; then
    echo "Must specify a valid tag name. Aborting." && exit
  else
    TAGNAME=$response
    response="Y"
  fi
else
  # Confirm tag creation
  echo "Create tag ${bold}$TAGNAME${normal} for $DEPLOYMENT? [yN]" && read response
fi

if test "$response" = "Y" -o "$response" = "y"; then
  CMD="git tag -a $TAGNAME -m '$MSG';git push;git push origin --tags"
  SUBMODULE_CMD="git submodule foreach --recursive \"($CMD)\""

  echo ""
  echo "Tagging sub-repos:"
  echo $SUBMODULE_CMD;
  eval $SUBMODULE_CMD;
  echo ""
  echo "Tagging main repo:"
  echo $CMD;
  eval $CMD;
else
  echo "Received $response -- not Y, canceling." && exit
fi
