#!/bin/sh -e
#
# This script is put in the public domain by Henrik Nordström
# <hno@squid-cache.org>. It is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# If you find this script useful then you are encouraged to send feedback
# to the author, but you have absolutely no obligation to do so.
#
# Author:
#   Henrik Nordström <hno@squid-cache.org>
#   http://hem.passagen.se/hno/
#
# Distribution URL:
#   http://devel.squid-cache.org/CVS.html
#
# Version history:
#   2001-09-25	First public domain release
#
if [ $# -ne 2 ] && [ $# -ne 1 ]; then
   exec >&2
   echo "Usage: $0 base-tag [patchversion]"
   echo "    where base-tag is the name of the base branch"
   echo "    (usually HEAD, but you should know...)"
   echo "    If patchversion is specified then a patch tag will be created"
   echo "    for any remains in the branch."
   exit 1
fi
if [ ! -f CVS/Root ] || [ ! -f CVS/Repository ]; then
    exec >&2
    echo "ERROR: The script must be run from a CVS working directory"
    exit 1
fi
if [ -f CVS/Tag ]; then
    localtag=`cat CVS/Tag|cut -c2-`
else
    exec >&2
    echo "ERROR: The script can only be run from branches. Running"
    echo "it from the HEAD version does not make sense."
    exit 1
fi
rootdir=`cat CVS/Root|sed -e 's/.*://'`
module=`cat CVS/Repository|sed -e "s#^$rootdir##"`
mergefrom="$1"
tag="${localtag}"
mergetag="Z-${tag}_merge_${mergefrom}"
patchversion="$2"

ecvs() {
    echo cvs $* >&2
    cvs "$@"
}
eecvs() {
    echo cvs $* >&2
    cvs "$@" 2>/dev/null
}
o () {
    echo "# $*..."
}
o Check that there is no pending changes in the working directory
diffl=`eecvs -q diff | grep -v '^\?' | head | wc -l`
if [ "$diffl" -ne 0 ]; then
    echo "ERROR: There are pending changes in your working directory!"
    echo "You cannot close a branch you are currently working on."
    exit 1
fi

o Check if there is any remains in the branch
diffl=`eecvs -q rdiff -kk -r ${tag} -r ${mergetag} ${module} | head | wc -l`
if [ "$diffl" -ne 0 ]; then
    if [ -n "$patchversion" ]; then
	o Creating patch tag
	patchtag="${tag}-${patchversion}"
	patchmergetag="Z-${patchtag}_merge_${mergefrom}-$patchversion"
	ecvs -q rtag -r "$mergetag" $patchmergetag $module || true
	ecvs -q rtag -r "$localtag" $patchtag $module || true
    else
	echo "ERROR: There are remains in the branch. Cannot close without"
	echo "       a patch name for the remains"
	exit 1
    fi
fi

o Close down the branch
ecvs -q rtag -d Z-${tag}_merge-new_${mergefrom} ${module}
ecvs -q rtag -d Z-${tag}_merge-old_${mergefrom} ${module}
ecvs -q rtag -d Z-${tag}_merge_${mergefrom} ${module}
ecvs -q rtag -d ${tag} ${module}