#!/bin/sh
# $Id$
#

# sanity check to insure that the user invoked this from somewhere within
# the qgis source hieararchy

if [ ! -f CVS/Repository -a ! `grep qgis CVS/Root` ]; then
        echo "You are not in a qgis source directory!"
        exit -1
fi

#
# Get Changes
#

# This will hold the diffs between what's to be checked in and currently in the repository.
TMPFILE=`mktemp /tmp/qgis-commit-tmp.XXXXXXXXXX`

echo "************************************************************" > ${TMPFILE}
echo "Please write above that line of stars! Rest will be removed." >> ${TMPFILE}

cvs diff $@ 2> /dev/null | sed -e "/^?/d" -e "/^Index: /d" >> ${TMPFILE}

if [ $? -ne 0 ]; then 
  echo cvs diff failed;
  rm $TMPFILE;
  exit -2
fi

${EDITOR} ${TMPFILE}

if [ $? -ne 0 ]; then 
  echo edit session failed;
  rm $TMPFILE;
  exit -3
fi

#
# Increment the extra version number in the configure.in; also add the message along
# with the version number to the ChangeLog.
#

# find out where the top directory is
WAY2ROOT="`dirname $PWD | sed -e 's#\(.*\)\/qgis.*#\1#'`/qgis"

# if we're not already in the top directory, push the current directory on stack and 
# cd to the top directory
if [ "a${WAY2ROOT}" != "a" ]; then
	pushd $WAY2ROOT > /dev/null
fi

# The top level directory *should* contain a configure.in; if not, then something went
# horribly awry.
if [ ! -f configure.in ]; then
	popd
	echo "Not in qgis top directory!"
        rm $TMPFILE
	exit -4
fi

# Get the user's sourceforge username.
NAME=`sed -e 's/.*:\([^:]*\)@.*/\1/' CVS/Root`

MAJOR_VERSION=`sed -n -e 's/MAJOR_VERSION=//p' configure.in`
MINOR_VERSION=`sed -n -e 's/MINOR_VERSION=//p' configure.in`
MICRO_VERSION=`sed -n -e 's/MICRO_VERSION=//p' configure.in`
EXTRA_VERSION=`sed -n -e 's/EXTRA_VERSION=//p' configure.in`


# I *think* this means that if the user *didn't* specify any files, then add in
# the ChangeLog and configure.in.  
# XXX I'm not sure why this should be done.

if [ "a$@" != "a" ]; then
	EXTRAS="$WAY2ROOT/ChangeLog $WAY2ROOT/configure.in"
else
	EXTRAS=""
fi

#
# Change Extra Version
#

# increment extra version in configure.in

NEXTRA_VERSION=`expr ${EXTRA_VERSION} + 1`
sed -e "/EXTRA_VERSION=/s/${EXTRA_VERSION}/${NEXTRA_VERSION}/" configure.in > configure.in.tmp
mv configure.in.tmp configure.in


CLINES=`wc -l ChangeLog | awk '{print $1}'`
DIFFLINES=`expr $CLINES - 4`
DATE=`date +%F`
MSG=`sed -e '/\*\{20\}/,$d' ${TMPFILE}`

head -n 5 ChangeLog > ChangeLog.tmp
echo "${DATE} [${NAME}] ${MAJOR_VERSION}.${MINOR_VERSION}.${MICRO_VERSION}devel${NEXTRA_VERSION}" >> ChangeLog.tmp
echo "${MSG}" >> ChangeLog.tmp
tail -n $DIFFLINES ChangeLog >> ChangeLog.tmp
mv ChangeLog.tmp ChangeLog

#
# Commit
#

if [ "a${WAY2ROOT}" != "a" ]; then
	popd
fi

cvs commit -m "${MSG}" $@ ${EXTRAS}

rm ${TMPFILE}