#!/bin/sh
# Freeze - Lock a whole repository for backup.

KEYMAGIC=$$
TMPFILE=/tmp/freeze.$KEYMAGIC
bail_out () {
	# Exit abruptly. Return a failure code and display
	# an error message.
	echo "$1"
	rm -f $TMPFILE
	exit 1
}

freeze_directory () {
	echo "FREEZE: $1"
	# Obtain the master lock
	mkdir "$1/#cvslock"
	if [ $? != 0  ]
		then
                # Could not get master lock
		return 1
		fi
	# Create the readlock
	touch "$1/#cvs.rfl.$KEYMAGIC"
	# Record it in case of trouble
	echo $1 >> $TMPFILE
	rmdir "$1/#cvslock"
	return 0
}

thaw_repository () {
	# If we encounter anyone else playing with the
	# CVS locks during this, then there's a small risk
	# of deadlock. In that event, we should undo everything
	# we've done to the repository, wait and try again.
	# This function removes all the locks we've produced during
	# the run so far.
	for dir in `cat $TMPFILE`
		do
		echo "** THAW ** $dir"
		mkdir "$dir/#cvslock"
		if [ $? ]
			then
			# Remove readlock
			rm -f "$dir/#cvs.rfl.$KEYMAGIC"
			# Remove masterlock
			rmdir "$dir/#cvslock"
			fi
		done
	return 0
}

freeze_repository () {
	for dirname in `find $CVSROOT/$REPOSITORY -type d ! -iname CVS ! -iname Attic ! -iname "#cvslock"`
		do
		freeze_directory $dirname
		if [ $? != 0 ]
			then
			# We couldn't get the master lock.
			# Someone else must be working on the
			# repository
			thaw_repository
			return 1
			fi
		done
	return 0
}

if [ "$CVSROOT" == "" ]
	then
	echo "No CVSROOT specified in the environment"
	bail_out "Aborting"
	fi

if [ "$KEYROOT" == "" ]
	then
	KEYROOT="$CVSROOT"
	fi

if [ "$1" == "" ]
	then
	echo "No Repository specified."
	echo "Usage: $0 repository"
	bail_out "Aborting"
else
	REPOSITORY="$1"
	fi

# Double-check the validity of supplied paths
KEYFILE=$KEYROOT/.$REPOSITORY
test -d $CVSROOT || bail_out "Can't access $CVSROOT - is it a directory?"
touch $KEYFILE || bail_out "Can't access $KEYFILE - aborting"

TRIES=0
while	! freeze_repository
	do
	let TRIES=$TRIES+1
	echo "Could not freeze. Repository in use. (Attempt $TRIES)"
	if [ $TRIES -gt 9 ]
		then
		bail_out "Giving up"
		fi
	echo " Sleeping 1 second."
	sleep 1
	rm -f $TMPFILE
	echo "Trying again.."
	done
echo "** Repository $REPOSITORY frozen"
echo "$KEYMAGIC" >> $KEYROOT/.$REPOSITORY

rm -f $TMPFILE
exit 0

