#!/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
{
#
# There is a bug in diff3prog. It does not understand names longer than 29 characters.
# So, we create links with short names to the actual files.
#
	ln -s "$1" C$$.tmp
	ln -s "$2" A$$.tmp
	ln -s "$3" P$$.tmp
	$DIFF3 -E /tmp/d3a$$ /tmp/d3b$$ C$$.tmp A$$.tmp P$$.tmp $4 $5
	echo w
} | ed - "$1"
#
# Replace short names in the resulting files with the actual (long) names.
#
grep "C$$.tmp" "$1" >/dev/null
if ( test $? -eq 0 ) ; then
{
	echo 1,.s@C$$.tmp@$1@g
	echo w
} | ed - "$1"
fi
grep "P$$.tmp" "$1" >/dev/null
if ( test $? -eq 0 ) ; then
{
	echo 1,.s@P$$.tmp@$3@g
	echo w
} | ed - "$1"
fi
#	5.0 doesn't exit with the correct number of conflicts.  Get the
#	correct number.
	num=`grep -c '^<<<<<<<' "$1"`

	rm -f C$$.tmp A$$.tmp P$$.tmp
	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
