#!/usr/bin/env bash

set -eo pipefail

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 -E "^[0-9]+\.[0-9]+\.[0-9]+$") ]]; then
    echo $exact_tag
    exit 0
fi

if [[ $(echo ${exact_tag} | grep -E "^[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}"
