#!/bin/sh

set -e

TZ=UTC

# Verify clean tree
[ -z "$(git status --porcelain)" ] || ( echo >&2 "Git tree not clean!" && exit 1 )

# Get current branch name, preferring GitHub Actions env var if available
CURRENT_BRANCH=${GITHUB_REF_NAME:-$(git branch --show-current)}

# Get short SHA, preferring GitHub Actions env var if available
SHA=${GITHUB_SHA:-$(git rev-parse HEAD)}
SHORT_SHA="$(echo "${SHA}" | cut -c1-8)"

# Use gitcalver if we are on main
if [ "${CURRENT_BRANCH}" = main ]; then
    TZ=UTC
    # Prints version in the following format: <DAY>.<COMMIT#>_<SHA>
    # From docker docs: A tag name may contain lowercase and uppercase characters,
    # digits, underscores, periods and dashes. A tag name may not start with a period
    # or a dash and may contain a maximum of 128 characters.
    git log --pretty="format:%cd %h" --date="format-local:%Y%m%d" | \
        awk 'NR==1{d=$1;h=$2}{if(d==$1)c++;else exit}END{print d"."c"_"h}'
else
    printf "$(printf "${CURRENT_BRANCH}" | tr / -)_${SHORT_SHA}"
fi
