#!/bin/sh
# Unfreeze - Unlock a whole repository.


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


unfreeze_directory () {
	echo "UNFREEZE: $1"
	mkdir "$1/#cvslock"
	if [ $? != 0  ]
		then
		# Could not get master lock
		return 1
		fi
	test -f "$1/#cvs.rfl.$KEYMAGIC" || echo "THAW: Expected to find a lockfile: $1/#cvs.rfl.$KEYMAGIC"
	# Proceed anyway.
	rm -f "$1/#cvs.rfl.$KEYMAGIC"
	rmdir "$1/#cvslock"
	return 0
}

unfreeze_repository () {
	TMPFILE=/tmp/freeze.$KEYMAGIC
	for dirname in `find $CVSROOT/$REPOSITORY -type d ! -iname CVS ! -iname Attic ! -iname "#cvslock"`
		do
		unfreeze_directory $dirname
		if [ $? != 0 ]
			then
			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?"
test -f $KEYFILE || bail_out "No $KEYFILE appears to exist. Repository does not appear to be frozen"
TRIES=0

# Walk through each of the keys that the repository has been frozen with
# and unlock each one in turn. A single run of unfreeze, thaws multiple
# runs of freeze.
for KEYMAGIC in `cat $KEYFILE`
	do
	unfreeze_repository 
	if [ "$?" = "1" ]
		then
		echo "** Unable to obtain master locks for all directories."
		let TRIES=$TRIES+1
		if [ "$TRIES" = "10" ]
			then
			bail_out "Too many attempts. Giving up."
			fi
		sleep 1
		echo "** Trying again."
	else
		echo "** Repository $REPOSITORY thawed from freeze $KEYMAGIC"
		fi
		
	done
echo "** Unfreeze complete"
echo "** Repository $REPOSITORY thawed"
rm -f $KEYFILE
exit 0

