#!/bin/bash
set -o nounset  \
    -o errexit  \
    -o pipefail

REGEX_TAG='v[[:digit:]]+\.[[:digit:]]\.[[:digit:]]'

function semver_tags()
{
  {
    # Sometimes several release tags point to the same commit (see v1.9.0 and
    # v1.9.1). This iterates through each tag and ensures that it conforms to
    # semantic versioning requirements. Afterwards, the tags are sorted from
    # latest to earliest. This is so packages use the latest version tag.
    for tag in $(git tag --points-at HEAD)
    do
      if [[ ${tag} =~ ^${REGEX_TAG}$ ]]
      then
        printf '%s\n' "${tag}"
      fi
    done
  } | sort --version-sort --reverse
}

TAG=$(head -n 1 <<<"$(semver_tags)")

# If no tag could be found for the corresponding commit, assume that this
# is being built from an unversioned branch. In which case, this will
# construct a version that is compatible with Debian versioning:
# ${PREFIX}-<< short commit hash >>
if [[ ${TAG:-} ]]
then
  cat <<EOF >>"${BASH_ENV}"
export VERSION="${TAG}"
export RELEASE=1
EOF
else
  cat <<EOF >>"${BASH_ENV}"
export VERSION="${PREFIX}-$(git rev-parse --short HEAD)"
export RELEASE=
EOF
fi
