#!/bin/sh

if [ ! -f SConstruct ] || [ ! -f gui/rosegardengui.cpp ]; then
    echo "ERROR: This script must be run from the top-level Rosegarden directory" 1>&2
    exit 1
fi

update_version=""

case $1 in
    [0-9]*)
	version="$1"
	update_version=1
	;;
    -e)
	version=`grep VERSION SConstruct|head -1|sed 's/^.*"\([^"]*\)" *$/\1/'|grep -v ' '`
	if [ -z "$version" ]; then
	    echo "ERROR: Failed to extract version number from SConstruct"
	    exit 1
	fi
	;;
    *)
	echo 1>&2
	echo "`basename $0`: Build a release tarball of Rosegarden from CVS HEAD" 1>&2
	echo 1>&2
	echo "Usage:" 1>&2
	echo "    `basename $0` <version>" 1>&2
	echo "    `basename $0` -e" 1>&2
	echo "Where <version> is a number such as 1.0 or 2.5.1rc2 (without 4- prefix)." 1>&2
	echo "Use -e to extract the version number from SConstruct.  Otherwise SConstruct" 1>&2
	echo "will be updated with the new version number." 1>&2
	echo 1>&2
	exit 1
	;;
esac

tmpdir="release_tmp_$$"
rgname="rosegarden-4-$version"

echo "Building tarball for $rgname..."

tarname="$rgname.tar.bz2"
cvstag=RELEASE_V4_R`echo "$version" | sed 's/[\.-]/_/g'`

echo "[Tarball file will be $tarname]"
echo "[CVS tag will be $cvstag]"

if [ -f "$tarname" ]; then
    echo "ERROR: Tarball file $tarname already exists, exiting" 1>&2
    exit 1
fi

mkdir "$tmpdir" || exit 1
cd "$tmpdir"

echo "Checking out current CVS HEAD..."
CVSROOT=`cat ../CVS/Root` cvs -z3 co -P rosegarden
mv rosegarden "$rgname"

cd "$rgname"
if [ -n "$update_version" ]; then
    echo "Updating version number in SConstruct..."
    perl -i -p -e 's/^VERSION = "[^"]*"\s*$/VERSION = "4-'"$version"'"\n/' SConstruct
    cvs -z3 commit -m "Update version number for $version" SConstruct
fi

echo "Tagging CVS with tag $cvstag..."
cvs rtag "$cvstag" .

echo "Bundling up..."
cd ..
tar cvjf "$tarname" "$rgname" --exclude=RGbuild --exclude=CVS --exclude=.svn --exclude=web --exclude=docs/test --exclude=admin || exit 1

echo "Tidying..."
cd ..
mv "$tmpdir/$tarname" .
rm -rf "$tmpdir"

echo "Done, tarball is $tarname"
