#!/usr/bin/env bash
#
# Merge two files.
# Copyright (c) Linus Torvalds, 2005
#
# This is the per-file merge script, called with
#
#   $1 - original file SHA1 (or empty)
#   $2 - file in branch1 SHA1 (or empty)
#   $3 - file in branch2 SHA1 (or empty)
#   $4 - pathname in repository
#   $5 - original permissions
#   $6 - new permissions in branch1
#   $7 - new permissions in branch2
#
# We are designed to merge $3 _to_ $2, so we will give it
# a preference.
#
#
# Handle some trivial cases.. The _really_ trivial cases have
# been handled already by git-read-tree, but that one doesn't
# do any merges that migth change the tree layout
#

. ${COGITO_LIB}cg-Xlib

# if the directory is newly added in a branch, it might not exist
# in the current tree
dir=$(dirname "$4")
mkdir -p "$dir" || exit


error () {
	echo "MERGE ERROR: $@" >&2
}


case "${1:-.}${2:-.}${3:-.}" in
#
# deleted in both
#
"$1..")
	error "$4 is removed in both branches"
	error "This is a potential rename conflict"
	exit 1
	;;
#
# deleted in one and unchanged in the other
#
"$1.$1" | "$1$1.")
	#echo "Removing $4"
	rm -f -- "$4" && exec git-update-cache --remove -- "$4"
	;;

#
# added in one
#
".$2." | "..$3" )
	case "$6$7" in *7??) mode=+x;; *) mode=-x;; esac
	#echo "Adding $4 with perm $mode"
	rm -f -- "$4" &&
		git-cat-file blob "$2$3" >"$4" &&
		chmod "$mode" -- "$4" &&
		exec git-update-cache --add -- "$4"
	;;
#
# Added in both (check for same permissions)
#
".$2$2")
	case "$6" in *7??) mode=+x;; *) mode=-x;; esac
	#echo "Adding $4 with perm $mode"
	rm -f -- "$4" &&
		git-cat-file blob "$2" >"$4" &&
		chmod "$mode" -- "$4" &&
		git-update-cache --add -- "$4"
	ret=$?
	if [ "$6" != "$7" ]; then
		error "Added in both branches, permissions conflict $6->$7"
		[ "$ret" ] || ret=1
	fi
	exit $ret
	;;

#
# Modified in both, but differently ;(
#
"$1$2$3")
	echo "... Auto-merging $4"
	orig=$(git-unpack-file $1)
	src1=$(git-unpack-file $2)
	src2=$(git-unpack-file $3)
	ret=0
	if [ "$6" != "$7" ]; then
		error "Permissions conflict: $5->$6 here but merging $7"
		ret=1
	fi
	case "$6" in *7??) mode=+x;; *) mode=-x;; esac
	chmod "$mode" "$src2"

	if ! merge "$src2" "$orig" "$src1"; then
		ret=1
		# The user already gets the warning from merge itself and
		# from merge-cache too. This is too much.
		#error "Auto-merge failed"
		mv -- "$src2" "$4"

	elif ! mv -- "$src2" "$4" || ! git-update-cache --add -- "$4"; then
		ret=1
		error "Choosing $src2 -> $4 failed"
	fi
	rm "$orig" "$src1"
	exit $ret
	;;

*)
	error "$4: Not handling case $1 -> $2 -> $3"
	;;
esac
exit 1
