#!/bin/sh

# This script is used during compilation to generate the version string.  It
# creates a 'version.h' file that contains this string and is then linked into
# each build artifact.  Dynamic version string generation gives us the ability
# to indicate the git branch, uncommitted changes, and any other additional
# information that might be useful.

# The file which will contain the generated version string.
VERSION_FILE="version.h"

# The base version, which is generally the last release.
BASE_VERSION="7.1"

# If the user specifies OVERRIDE_VERSION, this will be used instead of the
# BASE_VERSION.  Anything found in EXTRA_VERSION is tacked onto the end.
EXTRA_VERSION="."${EXTRA_VERSION}
[ "${EXTRA_VERSION}" = "." ] && EXTRA_VERSION=""
VERSION="${OVERRIDE_VERSION:=$BASE_VERSION}${EXTRA_VERSION}"

if which git >/dev/null 2>&1 && test -d ../.git; then
    BRANCH="$(git symbolic-ref -q HEAD)"
    BRANCH="${BRANCH##refs/heads/}"
    BRANCH="${BRANCH:-HEAD}"
    VERSION="${VERSION} ${BRANCH} $(git rev-parse --short HEAD)"
    git update-index -q --refresh
    if test -n "$(git diff-index --name-only HEAD --)"; then
        VERSION="$VERSION-dirty"
    fi
fi

VERSION_STRING="#define BLKSNAP_VERSION \"$VERSION\""
if [ -e $VERSION_FILE ]; then
	OLD_VERSION_STRING=$(head -n 1 $VERSION_FILE | tr -d '\n')
fi

if [ "$VERSION_STRING" != "$OLD_VERSION_STRING" ]; then
	echo "$VERSION_STRING" > "$VERSION_FILE"
	echo "  GEN     $VERSION_FILE"
fi
