#!/usr/bin/env bash

set -eo pipefail

if git version | grep 'git version 1' >/dev/null; then
  # Old version of git. This will cause errors in the git1.8-test CI job, so if we're executing in CI, let's just
  # ignore it as the job does not require this info
  [ -n "${CI}" ] && exit 0
fi

version=$(cat VERSION || echo dev | sed -e 's/^v//g')
exact_tag=$(git describe --exact-match 2>/dev/null | sed -e 's/^v//g' || echo "")

if echo "${exact_tag}" | grep -qE "^[0-9]+\.[0-9]+\.[0-9]+$"; then
    echo "$exact_tag"
    exit 0
fi

if echo "${exact_tag}" | grep -qE "^[0-9]+\.[0-9]+\.[0-9]+-rc[0-9]+$"; then
    echo "$exact_tag"
    exit 0
fi

last_tag=$(git describe --abbrev=0 --exclude='*-rc*')
commits=$(git rev-list --count "${last_tag}..HEAD")
revision=$(git rev-parse --short=8 HEAD || echo unknown)

echo "${version}~beta.${commits}.g${revision}"
