#!/bin/sh
#
# Copyright (c) 1993 InterSoft Co.  All Rights Reserved
# THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF InterSoft Co.
# The copyright notice above does not evidence any
# actual or intended publication of such source code.
#
# $Id: checkout.sh,v 1.5 1996/08/27 16:33:16 hernan Exp $
#
#	checkout [-h|-?|-t|-p|-e|-u|-v version] files
#	where:
#
#	h ?		Help
#	t		Test for availability only
#	p		Print to stdout
#	e		Retrieve editable version
#	u		Undo checkout
#	a		Annotate specified version of file
#	v		Retrieve specified version
#
#
# Version for the CVS Concurrent Version System
#
DELTA=""
KEEP=""
EDIT=""
VERSION=""
STDOUT=""
UNDO=""
TEST=""
ANOTATE=""
USAGE="Usage: `basename $0` [-h|-?|-t|-p|-e|-u|-a|-v version] files"
SAVEPWD=`pwd`
RET=0

while getopts h?tpeuav: OPT
do
	case $OPT in
	e)
		EDIT="1"
		;;
	u)
		UNDO="-u"
		;;
	v)
		VERSION=-r$OPTARG
		;;
	p)
		STDOUT="-p"
		;;
	t)
		TEST="1"
		;;
	a)
		ANNOTATE="1"
		;;
	h|\?)
		echo $USAGE 1>&2
		exit 1;
		;;
	esac
done

shift `expr $OPTIND - 1`

if [ $# -eq 0 ]
then
	echo $USAGE 1>&2
	exit 1
fi

for i
do
	DIR=`dirname $i`
	FILE=`basename $i`
	cd $SAVEPWD
	cd $DIR
	if [ $? -ne 0 ]
	then
		RET=1
		continue
	fi

	if [ \! -r "CVS/Entries" ]
	then
		RET=4
		continue
	fi
	grep "^/$FILE/" CVS/Entries >/dev/null 2>/dev/null
	EXISTS=$?
	if [ -n "$TEST" ]
	then
		if [ $EXISTS -ne 0 ]
		then
			echo "File $FILE is not under CVS control" 1>&2
			RET=2
			continue
		fi
	else
		# check for writable file when locking
		if [ -n "$EDIT" ]
		then
			if [ -w $FILE ]
			then
				echo "Writeable $FILE exists" 1>&2
				RET=5
				continue
			fi
		fi
		if [ -n "$ANNOTATE" ]
		then
			cvs annotate $VERSION $FILE 2>/dev/null
		else
			if [ -n "$STDOUT" ]
			then
				#
				# Get the repository specification
				# keeping only the directory specification
				# (ignoring method/user/host).
				#
				# (using sed instead of shell substitution because not
				# all /bin/sh's have it!)
				#
				ROOT=`cat CVS/Root | sed 's/.*://'`
				#
				# Remove the repository's main directory ($ROOT).
				#
				REPOSITORY=`cat CVS/Repository | sed "s:^$ROOT\/::"`
				#
				# And at last we can cvs co -p! :)
				#
				cvs co $VERSION -p $REPOSITORY/$FILE 2>/dev/null
			else
				if [ -n "$UNDO" ]
				then
					cvs unedit $FILE
				else
					cvs edit $FILE
				fi
			fi
		fi
		if [ $? -ne 0 ]
		then
			RET=3
			continue
		fi
	fi
done
exit $RET
