#!/usr/bin/env sh

# get-docker-tag
#
# Produces a suitable Docker tag from a branch or tag name.
#
# Arguments:
#   $1: Commit ref name (GitLab's $CI_COMMIT_REF_NAME).
#   $2: Target environment. Appends "-dev" to tags when "development" is given.
#
# Outputs:
#   Desired Docker tag.
#
# Examples:
#   "get-docker-tag 9.0"            -> "9.0-edge"
#   "get-docker-tag 9.0.0"          -> "9.0.0"
#   "get-docker-tag feature/foo"    -> "feature-foo"
#   "get-docker-tag 9.0 development -> "9.0-dev"

CI_DOCKER_TAG=$(echo "$1" | sed -E "s/[^a-z0-9._-]+/-/gi" | tr '[:upper:]' '[:lower:]')

# Append "-dev" if this is a development build
if [ "$2" = 'development' ]; then
  CI_DOCKER_TAG=$(echo "$CI_DOCKER_TAG""-dev")
# Append "-edge" if this is a version branch, e.g. "9.0"
#   This will hold true for branch push pipelines, but not for
#   tag pipelines or non-version branches, which is what we want
elif echo "$CI_DOCKER_TAG" | grep -Eq "^[[:digit:]]+\.[[:digit:]]+$"; then
  CI_DOCKER_TAG=$(echo "$CI_DOCKER_TAG""-edge")
fi;

echo "$CI_DOCKER_TAG"
