#!/bin/bash

if [ $# -lt 1 ]; then
	echo "usage: git-find-last-same [branch1] branch2"
	exit
fi

if [ $# -lt 2 ]; then
	b1="HEAD"
	b2=$1
else
	b1=$1
	b2=$2
fi


l1=`git rev-list --reverse $b1..$b2`
c1=`echo "$l1" | wc -l`
if [ $? -gt 0 ]; then
	echo error in git
	exit
fi

l2=`git rev-list --reverse $b2..$b1`
c2=`echo "$l2" | wc -l`
if [ $? -gt 0 ]; then
	echo error in git
	exit
fi

if [ $c1 -eq 0 -a $c2 -eq 0 ]; then
	echo "Branch $b1 and $b2 are equal"
	exit
fi

if [ $c1 -eq 0 ]; then
	echo "Branch $b2 can be fast forward to $b1 in $c2 commits"
	exit
fi

if [ $c2 -eq 0 ]; then
	echo "Branch $b1 can be fast forward to $b2 in $c1 commits"
	exit
fi

if [ $c1 -gt $c2 ]; then
	s1="$l2"
	s2="$l1"
else
	s1="$l1"
	s2="$l2"
fi

t1=`echo "$s2" | sed -ne '1p' `
t2=`echo "$s2" | sed -ne '2,$p' `

for t1 in $s1; do
	t2=`echo "$s2" | sed -ne '1p' `
	s2=`echo "$s2" | sed -ne '2,$p' `
	if ! git diff --quiet $t1 $t2; then
		break
	fi
done

echo "first diff between $t1 and $t2"

t1=`git rev-list --max-count=1 $t1~1`
t2=`git rev-list --max-count=1 $t2~1`

echo "first same between $t1 and $t2"

