#!/usr/bin/env bash
# This script is called from tools/generateSourceTarball
# It is used to generate a ReleaseInfo.cmake file with commit information which
# enables compilation without needing to have git installed.

rm -f ReleaseInfo.cmake

# Get version description.
# Depending on whether you checked out a branch (dev) or a tag (release),
# "git describe" will return "5.0-gtk2-2-g12345678" or "5.0-gtk2", respectively.
gitDescribe="$(git describe --tags --always)"

# Get branch name.
# Will return empty if you checked out a commit or tag. Empty string handled later.
gitBranch="$(git symbolic-ref --short -q HEAD)"

# Get commit hash.
gitCommit="$(git rev-parse --short --verify HEAD)"

# Get commit date, YYYY-MM-DD.
gitCommitDate="$(git show -s --format=%cd --date=format:%Y-%m-%d)"

# Get number of commits since tagging. This is what gitDescribe uses.
# Works when checking out branch, tag or commit.
gitCommitsSinceTag="$(git rev-list --count HEAD --not $(git tag --merged HEAD))"

# Get number of commits since branching.
# Works when checking out branch, tag or commit.
gitCommitsSinceBranch="$(git rev-list --count HEAD --not --tags)"

if [[ -z $gitDescribe ]]; then
    printf '%s\n' "Failed finding commit description, aborting."
    exit 1
fi
if [[ -z $gitBranch ]]; then
    printf '%s\n' "No branch found. Using commit description as branch name."
    gitBranch="$gitDescribe"
fi
if [[ -z $gitCommit ]]; then
    printf '%s\n' "Failed finding commit hash, aborting."
    exit 1
fi
if [[ -z $gitCommitDate ]]; then
    printf '%s\n' "Failed finding commit date, aborting."
    exit 1
fi

# Create numeric version.
# This version is nonsense, either don't use it at all or use it only where you have no other choice, e.g. Inno Setup's VersionInfoVersion.
# Strip everything after hyphen, e.g. "5.0-gtk2" -> "5.0", "5.1-rc1" -> "5.1" (ergo BS).
if [[ -z $gitCommitsSinceTag ]]; then
    gitVersionNumericBS="0.0.0"
else
    gitVersionNumericBS="${gitDescribe%%-*}" # Remove everything after first hyphen.
    gitVersionNumericBS="${gitVersionNumericBS}.${gitCommitsSinceTag}" # Remove everything until after first hyphen: 5.0
fi

cat <<EOF > ReleaseInfo.cmake
set(GIT_DESCRIBE $gitDescribe)
set(GIT_BRANCH $gitBranch)
set(GIT_COMMIT $gitCommit)
set(GIT_COMMIT_DATE $gitCommitDate)
set(GIT_COMMITS_SINCE_TAG $gitCommitsSinceTag)
set(GIT_COMMITS_SINCE_BRANCH $gitCommitsSinceBranch)
set(GIT_VERSION_NUMERIC_BS $gitVersionNumericBS)
EOF

printf '%s\n' "Git checkout information:" \
              "  Commit description:	${gitDescribe}" \
              "  Branch:		${gitBranch}" \
              "  Commit:		${gitCommit}" \
              "  Commit date:		${gitCommitDate}" \
              "  Commits since tag:	${gitCommitsSinceTag}" \
              "  Commits since branch:	${gitCommitsSinceBranch}" \
              "  Version (unreliable):	${gitVersionNumericBS}" \
              ""
