#!/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

gitDescribe="$1"

if [ -d .git ]; then
    # 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.
    if [ "$gitDescribe" = "" ]; then
        gitDescribe="$(git describe --tags --always)"
    fi

    # 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)"
elif [ -d .hg ]; then
    if [ "$gitDescribe" = "" ]; then
        gitDescribe="$(hg log -r . --template "{latesttag('re:.*v?[0-9.]+(rc)?[0-9]+$') % '{sub('^.*/.*:', '', tag)}{ifeq(distance, 0, '', '-')}{ifeq(distance, 0, '', count(revset('ancestors(\".\") and descendants(last(tag(r\"re:^v?[0-9]+[.][0-9.]+(rc[0-9]+)?$\"), 1))'))-1)}{ifeq(distance, 0, '', '-g')}{ifeq(distance, 0, '', short(gitnode))}'}")"
    fi

    gitBranch="$(hg log -r . --template "{activebookmark}")"
    gitCommit="$(hg log -r . --template "{short(gitnode)}")"
    gitCommitDate="$(hg log -r . --template "{date|shortdate}")"
fi

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

cat <<EOF > ReleaseInfo.cmake
set(GIT_DESCRIBE $gitDescribe)
set(GIT_BRANCH $gitBranch)
set(GIT_COMMIT $gitCommit)
set(GIT_COMMIT_DATE $gitCommitDate)
EOF

printf '%s\n' "Git checkout information:" \
              "  Commit description:	${gitDescribe}" \
              "  Branch:		${gitBranch}" \
              "  Commit:		${gitCommit}" \
              "  Commit date:		${gitCommitDate}" \
              ""
