#!/bin/sh

# notes:
# 
# I had an empty ../.svn directory, but don't use svn.  I think I made
# it to keep one of the makefiles happy.  if we check for git before
# svn, this isn't a problem.
#
# [ -nt ] is false if the 2nd file doesn't exist.  (it's true in bash,
# but not in sh) so let's make an old header file if it doesn't exist
# already
#
# my .git folder is 3 levels up (I am in
# ./synfig-studio/trunk/build_tools from the level it's at)
# so I added an extra case to test that case
#
# I merged most of the if's into a single extended if, and return once
# we find an scm folder if it has an old timestamp.  It doesn't make
# sense to determine that we're using git, but then to go on and look
# for a .svn folder just before the git timestamp is older than the header

HEADER="$2/autorevision.h"
SCM=none

if [ ! -f $HEADER ] ; then
	touch -t 197001010101 $HEADER
fi

if [ -f "$2/autorevision.conf" ] ; then
	SCM=manual
	. "$2/autorevision.conf"
elif [ -d "$1/.git/svn" ] ; then
	if [ ! "$1/.git/svn" -nt "$HEADER" ] ; then return ; fi
	SCM=git-svn
	REVISION=`cd "$1"; git-svn find-rev HEAD`
elif [ -d "$1/../.git/svn" ] ; then
	if [ ! "$1/../.git/svn" -nt "$HEADER" ] ; then return ; fi
	SCM=git-svn
	REVISION=`cd "$1/.."; git-svn find-rev HEAD`
elif [ -d "$1/../../.git/svn" ] ; then
	if [ ! "$1/../../.git/svn" -nt "$HEADER" ] ; then return ; fi
	SCM=git-svn
	REVISION=`cd "$1/../.."; git-svn find-rev HEAD`
elif [ -d "$1/.svn" ] ; then
	if [ ! "$1/.svn" -nt "$HEADER" ] ; then return ; fi
	SCM=svn
	REVISION=`cd "$1"; svnversion || svn info | sed -n 's/^Revision: \(.*\)/\1/p'`
elif [ -d "$1/_svn" ] ; then
	if [ ! "$1/_svn" -nt "$HEADER" ] ; then return ; fi
	SCM=svn
	REVISION=`cd "$1"; svnversion || svn info | sed -n 's/^Revision: \(.*\)/\1/p'`
fi

if [ x = "x$DEVEL_VERSION" ] ; then
	if [ x != "xREVISION" ] ; then
		if [ $SCM = svn ] ; then
			DEVEL_VERSION="SVN r$REVISION"
		elif [ $SCM = git-svn ] ; then
			DEVEL_VERSION="SVN r$REVISION (via git)"
		elif [ $SCM = manual ] ; then
			DEVEL_VERSION="$REVISION (manually configured)"
		fi
	fi
fi

if [ x != "x$DEVEL_VERSION" ] ; then
	echo "#define SHOW_EXTRA_INFO" > "$HEADER"
	echo "#define DEVEL_VERSION \"$DEVEL_VERSION\"" >> "$HEADER"
fi
