#!/bin/sh -e

progname=cvs-merge


# TODO - detect remerges automatically?
#      - make separate script cvs-merge-ci to do that?

#	KK=-kk
KK=
COMMIT=
REVERSE=
INC=
HELP=
while getopts Bbrhic opt
do
        [ "$opt" = "c" ] && COMMIT=1
        [ "$opt" = "r" ] && REVERSE="-r "
        [ "$opt" = "i" ] && INC="-i "
        [ "$opt" = "b" ] && KK=
        [ "$opt" = "B" ] && KK=-kk
	[ "$opt" = "h" ] && HELP=1
done
shift `expr "$OPTIND" - 1`

if [ -n "$REVERSE" -a -n "$INC" ]
then
	echo sorry, cannot reverse incremental merge, but you can reverse the whole change: >&2
	echo drop the -i >&2
	exit 1
fi

. cvs-tools-conf

help() {
	echo "syntax: $progname [options] target change 2>&1
-c    commit the merge
-r    reverse - unmerge
-i    incremental - remerge
-b    binary mode (use for binary files only) (on by default)
-B    not binary mode
-h    print this help"
}

if [ -n "$HELP" ]; then help; exit 0; fi
if [ ! -n "$2" ]; then help >&2; exit 1; fi

TARGET="$1"
JOB="$2"
shift 2

if [ "$TARGET" = HEAD ]
then
	REV=-A
else
	REV="-r $TARGET"
fi

cd "$CVS_TOOLS_CHANGES/$JOB"
MODULES=`find * -type d -mindepth 1 -maxdepth 1 -name CVS | sed 's/\/CVS//'`

if [ -n "$REVERSE" ]
then
	MERGE="-j $JOB -j ${JOB}_base"
	NAME="UNMERGE"
elif [ -n "$INC" ]
then
	MERGE="-j ${JOB}_merge_$TARGET -j $JOB"
	NAME="REMERGE"
else
	MERGE="-j ${JOB}_base -j $JOB"
	NAME="MERGE"
fi

if [ ! -n "$COMMIT" ]
then
	# do the merge
	mkdir -p "$CVS_TOOLS_LOCAL/$TARGET"
	cd "$CVS_TOOLS_LOCAL/$TARGET"
	(cvs -q co $REV $MODULES
	cvs -q update $KK $MERGE $MODULES 2>&1) |
	grep -v -e '^U ' -e '^retrieving revision'
	echo
	echo to commit, type:
	echo $progname -c $REVERSE$INC$TARGET $JOB
else
	# commit the merge
	msgfile=`tempfile -p cvst-`
	echo "$NAME: $JOB" > $msgfile
	editor $msgfile
	cd "$CVS_TOOLS_LOCAL/$TARGET"
	cvs -Q ci -m "`cat $msgfile`" $MODULES
	cd "$CVS_TOOLS_CHANGES/$JOB"
	cvs -Q tag -d "${JOB}_merge_$TARGET" $MODULES
	if [ ! -n "$REVERSE" ]
	then
		cvs -Q tag "${JOB}_merge_$TARGET" $MODULES
	fi
	rm $msgfile
fi
