#!/usr/bin/env bash
# shellcheck disable=SC1090
# Use the unofficial bash strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail; export FS=$'\n\t'

STEP=$1
IMAGE=$2
VERSION=$3

function stderr(){
  (>&2 echo -e "$1")
}

function usage() {
  stderr "./getTag.sh (minor|major) image version, e.g."
  stderr "\t./getTag.sh minor docker-registry.eccenca.com/eccenca-base v3.3.3"
}

function printVersion() {
  echo "${IMAGE}:$1"
}

pattern="^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9a-z]+)?$"
# if last tag does not match semver pattern, die
if [[ ! "$VERSION" =~ $pattern ]]; then
    stderr "WARN: last git tag ($VERSION) is not a semver version ($pattern)"
    printVersion "$VERSION"
    exit 1
fi

# if last tag does contain pre-release part, die
if [[ $VERSION == *"-"* ]]; then
    stderr "WARN: git tag ($VERSION) contains a pre-release and cannot be bumped";
    printVersion "$VERSION"
    exit 1
fi

SEMVER_PARSED=( ${VERSION//./ } )

if [ "${STEP}" == "major" ]; then
  printVersion "${SEMVER_PARSED[0]}.${SEMVER_PARSED[1]}"
elif [ "${STEP}" == "minor" ]; then
  printVersion "${SEMVER_PARSED[0]}"
else
  stderr "ERROR: Step needs to be minor or major:"
  usage
  printVersion "$VERSION"
  exit 1
fi
