#!/bin/sh
#
# Copyright (c) Josef "Jeff" Sipek, 2007-2013
#

USAGE="[-x exclude-pattern]... [<patchname>]"
if [ -z "$GUILT_VERSION" ]; then
	echo "Invoking `basename "$0"` directly is no longer supported." >&2
	exit 1
fi

_main() {

cache="$GUILT_DIR/$branch/.graphcache.$$"
xclude="$GUILT_DIR/$branch/.graphexclude.$$"
trap "rm -rf \"$cache\" \"$xclude\"" 0
mkdir "$cache"
>"$xclude"

while [ $# -gt 0 ]; do
	if [ "$1" = "-x" ] && [ $# -ge 2 ]; then
		echo "$2" >> "$xclude"
		shift
		shift
	else
		break
	fi
done

if [ $# -gt 1 ]; then
	usage
fi

patchname="$1"

bottompatch=$(head_n 1 < "$applied")
if [ -z "$bottompatch" ]; then
	echo "No patch applied." >&2
	exit 1
fi

base=`git rev-parse "refs/patches/${branch}/${bottompatch}^"`

if [ -z "$patchname" ]; then
	top=`git rev-parse HEAD`
else
	top=`grep "^$patchname$" "$applied"`
	if [ -z "$top" ]; then
		die "Cannot find patch '$patchname'. Is it applied?"
	fi
fi

getfiles()
{
	git diff-tree -r "$1^" "$1" | cut -f2
}

disp "digraph G {"

current="$top"

safebranch=`echo "$branch"|sed 's%/%\\\\/%g'`
while [ "$current" != "$base" ]; do
	pname=`git show-ref | sed -n -e "
/^$current refs\/patches\/$safebranch/ {
	s:^$current refs/patches/$branch/::
	p
	q
}"`
	[ -z "$pname" ] && pname="?"

	pname="`printf \"%s\" \"$pname\" | sed 's/\"/\\\\\"/g'`"

	disp "# checking rev $current"
	disp "	\"$current\" [label=\"$pname\"]"

	# new "hash table"
	rm -f "$cache/dep"
	touch "$cache/dep"

	getfiles $current | grep -v -f "$xclude" | while read f; do
		# hash the filename
		fh=`echo "$f" | sha1 | cut -d' ' -f1`
		if [ -e "$cache/$fh" ]; then
			# ok, something already touched this file before us
			cat "$cache/$fh" >> "$cache/dep"
		fi
		echo "$current" > "$cache/$fh"
	done

	sort -u "$cache/dep" | while read h; do
		disp "	\"$h\" -> \"$current\"; // ?"
	done

	current=`git rev-parse $current^`
done

disp "}"

}
