#! /bin/sh

# sd file revision comparison script
#
# Author: (cc) Richard Jones http://www.cs.kent.ac.uk/~rej
# Copyright: This software is licensed under the 
# CC-GNU GPL version 2.0 or later
# http://creativecommons.org/licenses/GPL/2.0/

# Usage: sd [-dgvo] [-r<rev 1> [-r<rev2>]] [diff_flags] file
#
# Compare 2 revisions of a file, either with a diff or with an editor
# like sccs diffs file but uses gvim, vdiff or gnudiff.
# Options:
#	-d	Use diff
#	-g	Use gnudiff
#	-v	Use vdiff (from Kent software tools) 
#	-o	Use opendiff (for Mac OS X)
#	Default	Use gvim 

# Determine which differencer to use
if [ "X$1" = X-d ]; then
	diff=diff
	shift
elif [ "X$1" = X-g ]; then
	diff="gnudiff -u"
	shift
elif [ "X$1" = X-v ]; then
	diff="vdiff -t"
elif [ "X$1" = X-o ]; then
	diff="opendiff"
else
	diff="gvim --nofork -d"
fi

# Grab revision identifiers
case "$1" in
-r*)	rel1="$1"; shift ;;
*)	rel1=
esac

case "$1" in
-r*)	rel2="$1"; shift ;;
*)	rel2=
esac


# Grad any other flags
while :; do
	case "$1" in
	-*)
		diff_flags="$diff_flags $1"
		shift
		;;
	*)
		break
	esac
done

# Expect just a single file argument
test $# = 1 || { 1>&2 echo "Usage: sd [-dgv] [-r<rev 1> [-r<rev 2>]] file"; exit 1; }
file=$1

# Determine version control system
if [ -d .svn ]; then
	co='svn cat'
elif [ -d CVS ]; then
	co='cvs -Q update -p'
elif [ -d SCCS ]; then
	co='sccs get -s -p'
elif [ -d RCS ]; then
	co='co -p'
else 
	g="$(git rev-parse --git-dir 2>/dev/null)"
	if [ -z $g ]
	then
		echo "No SCCS, RCS, CVS or .svn directory; no git either" 1>&2
		exit 1
	else
		#get the path from git root to here
		wd=`pwd`
		g=`dirname $g`
		gitdir=${wd#$g/}

		#lose the -r from $rel*
		rel1=${rel1:2}
		rel2=${rel2:2}
	fi
	co='git cat-file blob'
fi	

# Get the first revision
tmp1=/tmp/sd$$${rel1//\//_}
if [ -z $g ]
then
	$co $rel1 $file > $tmp1
else
	$co $rel1:$gitdir/$file > $tmp1
fi

# Get the second revision if any, compare the files and remove temporaries
if [ X"$rel2" != X ]
then
	tmp2=/tmp/sd$$${rel2//\//_}
	if [ -z $g ]
	then
		$co "$rel2" $file > $tmp2
	else
		$co $rel2:$gitdir/$file > $tmp2
	fi
	$diff $diff_flags $tmp1 $tmp2
	rm -f $tmp2
else
	$diff $diff_flags $tmp1 $1
fi
rm -f $tmp1
