#!/bin/sh

VERSION_H=${1:-version.h}
NEWFILE=`mktemp -t version.h.XXXXXXXXXX`

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\"" > $NEWFILE
	BR=`awk '/^branch:/ {printf("%s",$2);}' $HGA`
	echo "#define HG_BRANCH \"$BR\"" >> $NEWFILE
elif [ -d .hg ]; then
	HG=${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.
	VER=`$HG id -T"{latesttag}{if(latesttagdistance,'.{latesttagdistance}')}"`
	$HG log -r. -T"`cat version.t`" | sed "s/\$DELTA/$DELTA/" > $NEWFILE
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 $NEWFILE $VERSION_H
	sed "s/@VERSION@/$VER/" < mbuffer.1.in > mbuffer.1
	exit
fi

cmp -s $VERSION_H $NEWFILE

if [ "0" = "$?" ]; then
	echo version.h is up-to-date
	rm $NEWFILE
else
	echo updating version.h
	sed "s/@VERSION@/$VER/" < mbuffer.1.in > mbuffer.1
	mv -f $NEWFILE $VERSION_H
fi
