#!/bin/bash
#
# Make a log of changes in a GIT branch.
#
# This script was originally written by (c) Ross Vandegrift.
# Adapted to his scripts set by (c) Petr Baudis, 2005.
# Major optimizations by (c) Phillip Lougher.
#
# Takes an id resolving to a commit to start from (HEAD by default).

# regex for parent declarations
PARENTS="^parent [A-Za-z0-9]{40}$"

TMPCL=$(mktemp -t gitlog.XXXXXX)
TMPCM=$(mktemp -t gitlog.XXXXXX)
TMPCD=$(mktemp -t gitlog.XXXXXX)

# takes an object and generates the object's parent(s)
changelog () {
	local parents new_parent mylastprinted
	declare -a new_parent

	new_parent=("$@")
	parents=$#

	while [ $parents -gt 0 ]; do
		parent=${new_parent[$(($parents-1))]}
		echo $parent >> $TMPCL

		cat-file commit $parent >$TMPCM

		mylastprinted=$lastprinted
		ignoredparents=0
		parents=0
		printedcommit=0
		while read type text; do
			if [ "$type" = "" ]; then
				break;
			elif [ $type = 'tree' ]; then
				tree=$text
			elif [ $type = 'parent' ]; then
				diff-tree -r `tree-id $text` $tree $file >$TMPCD
				if [ -s $TMPCD ]; then
					if [ "$lastprinted" != "$parent" ]; then
						echo commit $parent child $lastprinted
						lastprinted=$parent
					fi
					cat $TMPCD | xargs -0 -n 1 echo
				fi
				
				if grep -q $text $TMPCL; then
					ignoredparents=$(($ignoredparents+1))
				else
					new_parent[$parents]=$text
					parents=$(($parents+1))
				fi
			fi
		done < $TMPCM
	        if [ "$lastprinted" = "$parent" ]; then
		    echo -e "\n--------------------------"
		fi
		i=0
		mylastprinted=$lastprinted
		while [ $i -lt $(($parents-1)) ]; do
			changelog ${new_parent[$i]}
			i=$(($i+1))
			lastprinted=$mylastprinted
		done
	done
}

file=$1
base=$(gitXnormid.sh -c $2) || exit 1

if [ -n "$3" ]; then
    endpoint=$(gitXnormid.sh -c $3) || exit 1
    if rev-tree $base $endpoint | grep -q $base:3; then
	base=
    else
	rev-tree --edges $base $endpoint | sed 's/[a-z0-9]*:1//g' > $TMPCL
    fi
fi
changelog $base
rm $TMPCL $TMPCM $TMPCD

