#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

OUTPUT=--quiet
if [ "${1:-}" = '--show-diff' ]; then
    OUTPUT=
fi

# If a tagged version, just print that tag
HEAD_TAGS=( $(git tag --points-at HEAD) )
case ${#HEAD_TAGS[@]} in
    0)  ;;

    1)  echo ${HEAD_TAGS[0]}; exit 0
	;;

    2) # For releases we may have two tags, one with an v prefix (e.g. v1.17.0 and 1.17.0),
       # discard the v prefix
       TAG1=${HEAD_TAGS[0]}
       TAG2=${HEAD_TAGS[1]}
       if [[ "${TAG1}" == v* && ${TAG1%$TAG2} == "v" ]]; then
           echo ${TAG2}; exit 0
       fi
       if [[ "${TAG2}" == v* && ${TAG2%$TAG1} == "v" ]]; then
           echo ${TAG1}; exit 0
       fi
       ;&

    *) echo "error: more than one tag pointing to HEAD" >&2; exit 1; ;;
esac



WORKING_SUFFIX=$(if ! git diff --exit-code ${OUTPUT} HEAD >&2; \
                 then echo "-wip"; \
                 else echo ""; \
                 fi)
BRANCH_PREFIX=$(git rev-parse --abbrev-ref HEAD)

# replace spaces with dash
BRANCH_PREFIX=${BRANCH_PREFIX// /-}
# next, replace slashes with dash
BRANCH_PREFIX=${BRANCH_PREFIX//[\/\\]/-}
# now, clean out anything that's not alphanumeric or an dash
BRANCH_PREFIX=${BRANCH_PREFIX//[^a-zA-Z0-9-]/}
# finally, lowercase with TR
BRANCH_PREFIX=`echo -n $BRANCH_PREFIX | tr A-Z a-z`

echo "$BRANCH_PREFIX-$(git rev-parse --short HEAD)$WORKING_SUFFIX"
