#!/bin/bash

# SPDX-FileCopyrightText: 2021 Robin Vobruba <hoijui.quaero@gmail.com>
#
# SPDX-License-Identifier: Unlicense

# Exit immediately on each error and unset variable;
# see: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -Eeuo pipefail
#set -Eeu

script_dir=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")

function _git_version() {

  repo_dir="${1:-.}"
  git \
    -C "$repo_dir" \
    describe \
    --long \
    --dirty \
    --candidates=99 \
    --always \
    --first-parent 2> /dev/null
}

# Environment file
env_file="${GITHUB_ENV:-}"

if [ -n "$GITHUB_REF" ]
then
    # Apparently, this is the right way to get a tag name. Really?
    # See: https://github.community/t5/GitHub-Actions/How-to-get-just-the-tag-name/m-p/32167/highlight/true#M1027
    our_version="${GITHUB_REF#refs/tags/}"
else
    our_version="$(_git_version)"
fi

if [ -n "$env_file" ]
then
  echo "OUR_VERSION=$our_version" >> $env_file
fi
echo -n "$our_version"
