#!/bin/sh

# changes [-iaw] file
#
# Runs filemerge on two versions of a file.
#
# -i prints the sccs history and prompts for versions to use.
# -a makes -i print all sccs history, instead of just the first 15 lines.
# -w makes the filemerge not read-only
#
# When -i is not used, the current file is compared to the previous sccs version
# of it.  When -i is used, hitting return when prompted for the new version
# gets you the current file, and hitting return when prompted for the old
# version gets you the previous sccs version.  If the file is not currently
# checked out (writable copy not present), then the latest sccs version is
# considered current.
#
# THIS SAMPLE PROGRAM IS BEING PROVIDED "AS IS" AND ONLY AS A COURTESY TO
# THE RECIPIENT.  SUN MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS 
# OR IMPLIED WITH RESPECT TO THIS SAMPLE PROGRAM INCLUDING QUALITY, PERF- 
# FORMANCE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON- 
# INFRINGEMENT.  IN NO EVENT WILL SUN BE LIABLE FOR ANY DIRECT, INDIRECT,  
# SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR  
# INABILITY TO USE THIS SAMPLE PROGRAM.

rm=
status=1
trap '$rm; exit $status' 0
trap 'exit' 1 2 3 15

### Process the command line.
usage() {
	echo "usage: changes [-iaw] file" 1>&2
	exit
}

interactive=n
read_only=y
filter="head -15"
while getopts iaw opt
do
	case $opt in
	     i)	interactive=y;;
	     a) interactive=y; filter=${PAGER:-more};;
	     w)	read_only=n;;
	esac
	shift `expr $OPTIND - 1`
done

[ $# -eq 1 ] || { usage; }
file="$1"

### Get the latest two version numbers of the sccs file.
set -- dummy `sccs prt "$file" | sed -n 's/^D \([^	 ]*\).*/\1/p'`
shift
if [ -f "SCCS/p.$file" ]; then
	newver="checked-out"
	newfile="$file"
else
	newver=$1
	newfile=/tmp/changes$$new
	shift
fi
oldver=$1
oldfile=/tmp/changes$$old

### If -i, show sccs history and ask user for versions.
if [ $interactive = y ]; then

	sccs prt $file | $filter

	echo "Enter version number for older version [$oldver]: \c"
	read response
	if [ -n "$response" ]; then
		oldver="$response"
	fi

	echo "Enter version number for newer version [$newver]: \c"
	read response
	if [ -n "$response" ]; then
		newver="$response"
		newfile="/tmp/changes$$new"
	fi
fi

### Get the old version.
rm="rm $oldfile"
sccs get -p -r"$oldver" "$file" > "$oldfile"

### Get the new version (unless they want the checked out file).
if [ "$newver" != "checked-out" ]; then
	rm="rm $oldfile $newfile"
	sccs get -p -r"$newver" "$file" > "$newfile"
fi

### Do the filemerge.
labels="-f1 $oldver -f2 $newver"
files="-a $oldfile $oldfile $newfile"
if [ $read_only = y ]; then
    filemerge -r $labels $files
else
    filemerge    $labels $files "$file+"
fi
status=0
