#!/bin/env bash
# A simple script to make a tag

me=$(basename "$0")
bin=$(cd "$(dirname "$0")" && /bin/pwd)
export PATH="$bin:$PATH"

err  () { echo 1>&2 "$*";   }
log  () { err "$me: $*"; }
fail () { log "$*"; exit 1; }
try  () { "$@" || fail "'$*' failed"; }
try_quiet  () { "$@" 2>&1 > /dev/null || fail "'$*' failed"; }

CURRENT=$(git describe --tags --abbrev=0 --match=v* HEAD)
usage() {
    err "Usage: $0 vX_Y_Z_ABCD"
    fail "Current tag is $CURRENT"
}
[ $# = 1 ] || usage
[ "$1" = "$CURRENT" ] && fail "New tag already exists."

TAG=$1
_TAG_NOV=${TAG/v/}
_TAG_NOV_DOTS=${_TAG_NOV//_/.}
_CURRENT_NOV=${CURRENT/v/}
_CURRENT_NOV_DOTS=${_CURRENT_NOV//_/.}
TOP=$(git rev-parse --show-toplevel)
VERSION_FILE=$TOP/drivers/net/ethernet/sfc/net_driver.h

contains () {
  local needle="$1"
  local haystack="$2"
  [ "$haystack" != "${haystack/$needle/X}" ] && return 0 || return 1
}

upgrade_version() {
  try sed -i "s/$_CURRENT_NOV_DOTS/$_TAG_NOV_DOTS/" $VERSION_FILE
  git diff
  try git commit -a -m "Driver tag $TAG"
  echo "Updated the EFX_DRIVER_VERSION, please remember to 'git push'"
}

# SANITY CHECKS
contains "v" "${TAG}" || fail "tag must contain 'v'"
contains "." "${TAG}" && fail "tag mustnot contain dots; use underscore"
gitstatus="$(git status --branch --porcelain)"
grep -q "^ M" <<< "${gitstatus}" && \
  fail "You have unstaged changes. Busted"
grep -q "^M[M ]" <<< "${gitstatus}" && \
  fail "You have uncommited/staged changes. Busted"
grep -q "^##.*\[ahead [0-9]*, behind" <<< "${gitstatus}" && \
  fail "Please 'git pull --rebase' to update your tree and apply your changes"
grep -q "^##.*\[ahead" <<< "${gitstatus}" && \
  fail "Please 'git push' your outgoing changes or cleanup your tree"
grep -q "^##.*\[behind" <<< "${gitstatus}" && \
  fail "Please 'git pull' to update your tree"
CURRENT_VERSION=$(grep EFX_DRIVER_VERSION $VERSION_FILE)
contains "$_CURRENT_NOV_DOTS" "$CURRENT_VERSION" && \
  upgrade_version $_CURRENT_NOV_DOTS $_TAG_NOV_DOTS
CURRENT_VERSION=$(grep EFX_DRIVER_VERSION $VERSION_FILE)
contains "$_TAG_NOV_DOTS" "$CURRENT_VERSION" || \
  fail "Please update net_driver.h with the EFX_DRIVER_VERSION you are tagging with"

git tag "${TAG}"
echo "TAGGED as ${TAG}"
echo "Please remember to 'git push --tags'"
echo "To inform the test team of this tag please update http://bugzilla.solarflarecom.com/bugzilla/show_bug.cgi?id=84731"
echo "Try 'git log --oneline --date-order --reverse $CURRENT..$TAG'"
