#!/bin/bash

sanitize_tag () {
    # a tag follows the same rules as a DNS domain name in terms of what's permitted to be in it
    tr -cs 'a-zA-Z0-9.-' '[-*]' \
    | sed -e 's|^[.-]*||' \
          -e 's|[.-]*$||' \
    | cut -c 1-63
}

if [[ $1 == -h || $1 == --help ]]; then
    echo "Print the current git branch, sanitized to be usable as a Docker image tag"
    echo
    echo "Usage: $(basename "$0") [<GIT_WD>]"
    exit 0
fi

tag=$(git -C "${1-}" symbolic-ref -q --short HEAD | sanitize_tag)

if [[ $tag == master || $tag == main ]]; then
    tag=latest
fi
if [[ $tag ]]; then
    echo "$tag"
    exit 0
else
    exit 1
fi

