#!/bin/sh -e
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 if there is any remains in the branch
diffl=`eecvs -z9 -q rdiff -kk -r ${tag} -r ${mergetag} ${module} | head | wc -l`
if [ "$diffl" -ne 0 ]; then
    if [ -n "$patchversion" ]; then
	o Creating patch tag
	tag="${tag}-${patchversion}"
	mergetag2="Z-${tag}_merge_${mergefrom}-$patchversion"
	ecvs -q rtag -r "$mergetag" $mergetag2 $module || true
	ecvs -q rtag -r "$localtag" $tag $module || true
	mergetag="$mergetag2"
    else
	echo "ERROR: There are remains in the branch. Cannot close without"
	echo "       a tag name for the remains"
	exit 1
    fi
fi

ecvs -z9 -q rtag -d Z-${tag}_merge-new_${mergefrom} ${module}
ecvs -z9 -q rtag -d Z-${tag}_merge_${mergefrom} ${module}
ecvs -z9 -q rtag -d ${tag} ${module}


