#! /bin/sh 
# Copyright (c) 2007 - 2009 Ralph Glasstetter, Michael Riepe
# This program is free software; see COPYING for details.
#
# Create a header file containing a version string, max. revision number and
# some timestamps of the project by scanning for the SVN "Id" keyword lines 
# of the files supplied as arguments.
#
# The script should be called during the build procedure by make, scons...
# therefore the output header file contains an artificial "Id" line from
# previous calls and is scanned additionally in case of incremental calls 
# with just a few changed (or no) files as arguments.

#@(#) $Id$

# location of this script (specify the input/output filenames below rel. to this!)
DIR=`dirname "$0"`

# Optional text file containing the version string of the last official release
VERSION_FILE="$DIR/VERSION"
# That's the output header file (which is also read if present!)
HEADER_FILE="$DIR/src/version.h"
# Default version string
VERSION=0.0.0

# Get VERSION from text file
[ -f "$VERSION_FILE" ] && read VERSION < "$VERSION_FILE"

# Append appropriate suffix
if [ -d $DIR/.svn ]
then VERSION="$VERSION-svn"
else VERSION="$VERSION-release"
fi

# maybe we want to know when the project was built?
BUILT=`TZ=UTC date '+%Y-%m-%d %H:%M:%SZ'`

# extract&analyse the Id keyword lines from the given source files
getids() {
	sed -ne 's,^[^ ]\+ \+\$Id: \(.*\) \$.*,\1,p' "$@" < /dev/null
	[ -f "$HEADER_FILE" ] && \
	  sed -ne 's,^#define LASTID \(.*\)$,\1,p' "$HEADER_FILE"
}
set -- $(getids "$@" | sort -k 2n,2 -k 3,4 -k 1,1 | tail -1)
NAME=$1
REVISION=$2
DATE=$3
TIME=$4
AUTHOR=$5
CHANGED="$3 $4"

cat <<EOF >$HEADER_FILE
/* This file was automatically generated by $0.
 * DO NOT EDIT!
 * Last changed source file (read on input) was:
 */

#define LASTID $NAME $REVISION $DATE $TIME $AUTHOR

#ifndef _VERSION_H
#define _VERSION_H

#define VERSION		"$VERSION"
#define REVISION	"$REVISION"
#define CHANGED		"$CHANGED"
#define BUILT		"$BUILT"

#endif /* _VERSION_H */
EOF

echo >&2 "Last change made on $DATE at $TIME in file '$NAME' by '$AUTHOR'"
echo >&2 "Prepared header file '$HEADER_FILE' for version/revision: $VERSION/$REVISION"

exit
