#!/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 -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*' --exclude='helpers/runner_wrapper/api/v*')
commits=$(git rev-list --count "${last_tag}..HEAD")
revision=$(git rev-parse --short=8 HEAD || echo unknown)

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