#!/bin/sh

# Find out if 4.x or 5.0
if [ -f /bin/ranlib ]; then
	fivedot0="FALSE"
else
	fivedot0="TRUE"
fi

PATH=/bin:/usr/bin
DIFF=/bin/diff

TEXTDOMAINDIR=`dirname $0`/../lib/locale
export TEXTDOMAINDIR

# Locate the diff3 program
if [ -x /usr/lib/diff3 ]
	then	DIFF3=/usr/lib/diff3
elif [ -x /usr/lib/diff3prog ]
	then	DIFF3=/usr/lib/diff3prog
else	printf "`gettext codemgr '%s: can't find diff3 program'`\n" $0;
	exit 1
fi

case $1 in
-p)
	p='1,w'
	shift
esac

case $# in
0|1|2)
	echo >&2 `gettext codemgr "merge: usage: merge [-p] file1 file2 file3"`
	exit 1
esac

case w in
w)
	if test ! -w $1
	then
		printf >&2 "`gettext codemgr '%s not writeable'`\n" $1
		exit 1
	fi
esac

umask 077

# These diffs are needed as input to lib/diff3 or lib/diff3prog
$DIFF $1 $3 >/tmp/d3a$$
case $? in
0|1) ;;
*) exit
esac

$DIFF $2 $3 >/tmp/d3b$$
case $? in
0|1) ;;
*) exit
esac

if [ ${fivedot0} = TRUE ]; then
{
	$DIFF3 -E /tmp/d3a$$ /tmp/d3b$$ $1 $2 $3 $4 $5
	echo w
} | ed - $1
#	5.0 doesn't exit with the correct number of conflicts.  Get the
#	correct number.
	num=`grep -c '^<<<<<<<' $1`
	case ${num} in
	0) ;;
	1) printf >&2 "`gettext codemgr 'merge: warning: 1 unresolved conflict during merge.'`\n";;
	*) printf >&2 "`gettext codemgr 'merge: warning: %d unresolved conflicts during merge.'`\n" ${num}
	esac
else
{
	$DIFF3 -E /tmp/d3a$$ /tmp/d3b$$ $1 $2 $3 $4 $5
	case $? in
	0) ;;
	1) printf >&2 "`gettext codemgr 'merge: warning: 1 unresolved conflict during merge.'`\n";;
	*) printf >&2 "`gettext codemgr 'merge: warning: %d unresolved conflicts during merge.'`\n" ${num}
	esac
	echo w
} | ed - $1
fi

rm -f /tmp/d3a$$ /tmp/d3b$$
exit 0
