#!/bin/sh

VERSION_H=${1:-version.h}

if [ -f .hg_archival.txt ]; then
	HGA=.hg_archival.txt
	# Gather version information from .hg_archival.txt for archives.
	TAG=`awk '/^tag:/ {printf("%s",$2);}' $HGA`
	LTAG=`awk '/^latesttag:/ {printf("%s",$2);}' $HGA`
	TAGD=`awk '/^latesttagdistance:/ {printf("%s",$2);}' $HGA`
	if [ "" != "$TAG" ]; then
		VER=$TAG
	elif [ "" = "$LTAG" ]; then
		echo archive has no tag or latesttag
		exit 1
	elif [ "0" != $TAGD ]; then
		VER=$LTAG.$TAGD
	else
		VER=$LTAG
	fi
	echo "#define VERSION \"$VER\"" > version.h.new
	BR=`awk '/^branch:/ {printf("%s",$2);}' $HGA`
	echo "#define HG_BRANCH \"$BR\"" >> version.h.new
elif [ -d .hg ]; then
	HG=`which hg`
	if [ "$?" != "0" ]; then
		echo "error: need mecurial to determine version"
		exit 1
	fi
	# Check if we have modified, removed, added or deleted files.
	if [ `$HG st -mard | wc -l` != "0" ]; then
		# add delta indicator
		DELTA="+"
	else
		DELTA=""
	fi
	# Gather version information from repository and sandbox.
	$HG log -r. -T"`cat version.t`" | sed "s/\$DELTA/$DELTA/" > version.h.new
else
	# Bail out with an error, if no version information an be gathered.
	echo "no version information available"
	exit 1
fi

if [ ! -f version.h ]; then
	echo creating version.h
	mv version.h.new $VERSION_H
	exit
fi

cmp -s $VERSION_H version.h.new

if [ "0" = "$?" ]; then
	echo version.h is up-to-date
	rm version.h.new
else
	echo updating version.h
	mv -f version.h.new $VERSION_H
fi
