#!/bin/sh -e
if [ $# -ne 1 ]; then
   echo "Usage: $0 merge-from"
   echo "    where merge-from is the branch you want to merge changes from"
   exit 1
fi
if [ ! -f CVS/Root ] || [ ! -f CVS/Repository ]; then
    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
    localtag=HEAD
fi
rootdir=`cat CVS/Root|sed -e 's/.*://'`
module=`cat CVS/Repository|sed -e "s#^$rootdir##"`
mergefrom="$1"
mergetag="Z-${localtag}_merge_${mergefrom}"
newtag="Z-${localtag}_merge-new_${mergefrom}"
oldtag="Z-${localtag}_merge-old_${mergefrom}"

ecvs() {
    echo cvs $* >&2
    cvs "$@"
}
o () {
    echo "# $*..."
}

o Check if there is any pending changes in the repository
diffl=`ecvs -z9 -q rdiff -kk -r ${mergetag} -r ${mergefrom} ${module} | wc -l`
if [ $diffl -eq 0 ]; then
    o No pending changes
    echo No pending changes > merge.log
    exit 0
fi

o Make sure there is no pending changes in the working directory
diffl=`ecvs -z9 -q diff -kk | grep -v '^\?' | wc -l`
if [ $diffl -ne 0 ]; then
    echo "ERROR: You must first commit any pending changes"
    exit 1
fi

o Make sure the working directory is up to date
ecvs -z9 -q update -kk -d -P 2>&1 | tee merge.log

o Set a temporary tag at the new version we are merging towards
ecvs -z9 -q rtag -F -r ${mergefrom} ${newtag} ${module}

o Merge changes into the working directory
ecvs -z9 -q update -kk -d -P -j ${mergetag} -j ${newtag} 2>&1 | tee -a merge.log

o Prune out RCS keywords
files=`find . -type f -print | xargs grep -l '\$Id:' || true`
if [ -n "$files" ]; then
    perl -i.orig -p -e 's/\$(Id|Revision):[^\$]*\$/\$$1\$/' $files
fi

o Checking for conflicts
if grep conflict merge.log; then
    echo "WARNING: CONFLICTS!"
    echo "Please correct the conflicts (see merge.log) and then exit from"
    echo "this shell to have the changes committed"
    $SHELL || true
fi

o Commit the changes
ecvs -z9 -q commit -m "Merged changes from ${mergefrom}"

o Move our baseline to the new version"(s)"
ecvs -z9 -q rtag -F -r ${newtag} ${mergetag} ${module}

echo "Done."


