#!/bin/sh

progname=$0
version=1.0.0
usage="\
Usage: $progname file
A simple shell script launches gtkdiff(1) for RCS(1) files.
This intends to be compatible with rcsdiff(1).
  -r N, --revision N         specifies revision numbers.
                             space between -r and N can be omitted.
                             The meaning follows rcsdiff(1).
  -h, --help                 print this help and exit
  -v, --version              print version information and exit"

# Command path
CO=@CO@
RM=@RM@
TR=@TR@
GTKDIFF=@prefix@/bin/gtkdiff

# Temporary files information
TMP_SUFFIX=@gtkdiff$$
REV1=
REV2=
TMP_REV1_FILE=
TMP_REV2_FILE=

finalize () {
	[ -n "$TMP_REV1_FILE" ] && [ -f $TMP_REV1_FILE ] && $RM -f $TMP_REV1_FILE
	[ -n "$TMP_REV2_FILE" ] && [ -f $TMP_REV2_FILE ] && $RM -f $TMP_REV2_FILE
	exit 1
}
trap finalize INT QUIT HUP TERM

#
# Option processing
#
while [ "$1" != "" ]
do
	case "$1" in
	-r | --revision)
		shift
		test $# -eq 0 && { echo "$usage"; exit 0; }
		[ -n "$REV1" ] && REV2="$1"
		[ -z "$REV1" ] && REV1="$1" ;;
	-r*)
		[ -n "$REV1" ] && REV2=`echo $1|$TR -d "\-r"`
		[ -z "$REV1" ] && REV1=`echo $1|$TR -d "\-r"` ;;
	-h | --help) 
		echo "$usage"; exit 0;;
	-v | --version | --v*)
		echo "$progname $version"; exit 0;;
	--) # Stop option processing.
		shift; break ;;
	*)
		break ;;
	esac
	shift
done

if [ -z "$1" ]
then
	echo "$usage"
	exit 1
fi

#
# Check necessary files
#
if [ ! -f "$1" ]
then
	echo "Warning:"
	echo "$1 not found"
	exit 0
fi

if [ ! -x "$CO" ]
then
	echo "Warning:"
	echo "You can't execute $CO."
	exit 0
fi

if [ ! -x "$GTKDIFF" ]
then
	echo "Warning:"
	echo "You can't execute $GTKDIFF."
	exit 0
fi


#
# Create temporary revision files
#
if [ -n "$REV1" ]
then
	TMP_REV1_FILE=/tmp/${1}"("${REV1}")"${TMP_SUFFIX}
	$CO -p$REV1 $1 > $TMP_REV1_FILE
else
	TMP_REV1_FILE=/tmp/${1}"("latest")"${TMP_SUFFIX}
	$CO -p $1 > $TMP_REV1_FILE
fi

if [ -n "$REV2" ]
then
	TMP_REV2_FILE=/tmp/${1}"("${REV2}")"${TMP_SUFFIX}
	$CO -p$REV2 $1 > $TMP_REV2_FILE
	$GTKDIFF $TMP_REV1_FILE $TMP_REV2_FILE
else
	$GTKDIFF $TMP_REV1_FILE $1
fi

finalize

exit 0


