#!/bin/sh

GIT=${GIT:-git}
SED=${SED:-sed}
AWK=${AWK:-awk}

if [ -f ${1}/.version ]; then
    cat ${1}/.version
    exit 0
fi

if [ ! -d ${1}/.git ]; then
    echo "UNKNOWN__and_probably_unsupported"
    exit 0
fi

if [ -z ${GIT} ]; then
    GIT="git"
fi

if ! command -v ${GIT} >/dev/null 2>&1; then
    echo "UNKNOWN__and_probably_unsupported"
    exit 1
fi

GITCHECK=$(${GIT} describe --always 2>/dev/null || echo gitfail 2>/dev/null)
if [ "x${GITCHECK}" = "xgitfail" ]; then
    echo "UNKNOWN__git_check_fail"
    exit 1
fi

cd ${1} || exit 1

MODIFIED=""

# If MAINLINE_BRANCH is already set in the environment, use it.
if [ -z "${MAINLINE_BRANCH}" ] ; then
    # Try to retrieve MAINLINE_BRANCH from a local .develvars file first.
    # .develvars is keyed by the branch name so we need to get that first.
    BRANCH=$(${GIT} symbolic-ref --short HEAD 2>/dev/null)
    if [ -f .develvars ] ; then
        MAINLINE_BRANCH=$(${GIT} config -f .develvars --get branch.${BRANCH}.mainline-branch)
    fi

    # If we didn't find it, see if this is a well-known development branch.
    # development/<mainline_branch>/<branchname> or
    # devel/<mainline_branch>/<branchname>
    if [ "x${MAINLINE_BRANCH}" = "x" ] ; then
        MAINLINE_BRANCH=$(echo "${BRANCH}" | ${SED} -n -r -e "s@devel(opment)?/([0-9]+)/.+@\2@p")
    fi

    # If we didn't find it, get it from configure.ac.
    if [ "x${MAINLINE_BRANCH}" = "x" ] ; then
        MAINLINE_BRANCH=$(${AWK} '/AC_INIT/ { print substr($2, 2, length($2) - 3) }' configure.ac)
    fi
fi

VERSION=`${GIT} describe --long --always --tags --dirty=M 2> /dev/null`
if [ $? -ne 0 ]; then
    if [ "`${GIT} ls-files -m | wc -l`" != "0" ]; then
        MODIFIED="M"
    fi
    # Some older versions of git do not support all the above
    # options.
    VERSION=`${GIT} rev-parse --short --verify HEAD`${MODIFIED}
fi
echo GIT-${MAINLINE_BRANCH}-${VERSION}
