#!/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

# 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	echo "$0: can't find diff3 program";
	exit 1
fi

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

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

case w in
w)
	if test ! -w $1
	then
		echo >&2 "$1 not writeable"
		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) echo >&2 merge: warning: 1 unresolved conflict during merge.;;
	*) echo >&2 merge: warning: ${num} unresolved conflicts during merge.
	esac
else
{
	$DIFF3 -E /tmp/d3a$$ /tmp/d3b$$ $1 $2 $3 $4 $5
	case $? in
	0) ;;
	1) echo >&2 merge: warning: 1 unresolved conflict during merge.;;
	*) echo >&2 merge: warning: $? unresolved conflicts during merge.
	esac
	echo w
} | ed - $1
fi

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