#!/bin/bash
set -e
set -x

# 
# Prep
#

# Create repo with one file
rm -rf repo
mkdir repo
cd repo
seq 0 9 > f
git init .
git add f
git commit -m start

function create_special_branch()
{
	name="$1"
	substexpr="$2"

	# Create
	git checkout -b $name master

	# Tweak the main file	
	perl -pi -e "$substexpr" f

	# Add something to the metadata file
	echo metadata-for-$name > m
	git add m

	git commit -a -m $name
}

# Create a couple of branches, each changes file "f" in a different way that
# don't conflict, and changes file "m" in a way that WOULD conflict (but we discard it later).
create_special_branch b1 's,0,0 - b1,'
create_special_branch b2 's,9,9 - b2,'

# Change the master too.
git checkout master
perl -pi -e 's,5,5-master,' f
git commit -a -m master

#
# Now do the merging
#

# Make sure nothing is lying around, as we do a reset --hard at the end.
test -z "$(git status --porcelain)" 

for b in b1 b2
do
        common=$(git merge-base HEAD $b)
# First approach
        git read-tree -m -i $common $b
# Second approach
#        git read-tree -m -i $common HEAD $b

	# Discard the metadata file
        git reset -q HEAD m
        rm -f m
done

# Write the tree
tree=$($debug git write-tree)

# Commit it as a merge of the two branches
commit=$(echo "Merged branches b1 and b2." | git commit-tree $tree -p b1 -p b2)

# Point the current branch at that commit
git reset --hard $commit

gitk --all
