#!/bin/bash

# Creates and updates the package_version information used by configure.ac
# (or other makefiles).  When run inside a git repository it will use the
# version information that can be queried from it unless AUTO_UPDATE is set
# to 'no'.  If no version is currently known it will be set to 'unknown'.
#
# If called with the argument 'release', the PACKAGE_VERSION will be updated
# even if AUTO_UPDATE=no, but the value of AUTO_UPDATE shall be preserved.
# This is used to force a version update whenever `make dist` is run.
#
# The exit status is 1 if package_version is not modified, else 0 is returned.
#
# This script should NOT be included in distributed tarballs, because if a
# parent directory contains a git repository we do not want to accidentally
# retrieve the version information from it instead.  Tarballs should ship
# with only the package_version file.
#
# Ron <ron@debian.org>, 2012.

SRCDIR=$(dirname $0)

if [ -e "$SRCDIR/package_version" ]; then
    . "$SRCDIR/package_version"
fi

if [ "$AUTO_UPDATE" = no ]; then
    [ "$1" = release ] || exit 1
else
    AUTO_UPDATE=yes
fi

# We run `git status` before describe here to ensure that we don't get a false
# -dirty from files that have been touched but are not actually altered in the
# working dir.
GIT_VERSION=$(cd "$SRCDIR" && git status > /dev/null 2>&1 \
                           && git describe --tags --match 'v*' --dirty 2> /dev/null)
GIT_VERSION=${GIT_VERSION#v}

if [ -n "$GIT_VERSION" ]; then

    [ "$GIT_VERSION" != "$PACKAGE_VERSION" ] || exit 1
    PACKAGE_VERSION="$GIT_VERSION"

elif [ -z "$PACKAGE_VERSION" ]; then
    # No current package_version and no git ...
    # We really shouldn't ever get here, because this script should only be
    # included in the git repository, and should usually be export-ignored.
    PACKAGE_VERSION="unknown"
else
    exit 1
fi

cat > "$SRCDIR/package_version" <<-EOF
	# Automatically generated by update_version.
	# This file may be sourced into a shell script or makefile.

	# Set this to 'no' if you do not wish the version information
	# to be checked and updated for every build.  Most people will
	# never want to change this, it is an option for developers
	# making frequent changes that they know will not be released.
	AUTO_UPDATE=$AUTO_UPDATE

	PACKAGE_VERSION="$PACKAGE_VERSION"
EOF
