# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  Backup - move file to backup
#
#SYNOPSIS
#  &Backup(filename);
#
#DESCRIPTION
#  We "back up" a file by appending a hyphen to its name. If that file exists,
#  we back it up recursively, to at more $buplim levels.
#
#  We use the global value $bdepth.  Perhaps we should make this a proper
#  module, and localize $bdepth.  Naaah...
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>

$bdepth = 0 unless defined $bdepth;
$buplim = 8 unless defined $buplim;

sub Backup {
	local($fil) = @_;
	local($bup) = "$fil-";
	local($F) = "$me/Backup";
	local($s) = 0;		# Return status.
	local($x);
	return 0 unless -f $fil;			# Can't back it up if it doesn't exist.
	if (++ $bdepth <= $buplim) {
		&Backup($bup) if (-f $bup);		# Recursive backup.
		if (link($fil,$bup)) {			# Link current name to backup name.
			print "$F: Linked \"$fil\" -> \"$bup\"\n" if $V>5;
			if ($x = unlink($fil)) {	# get rid of current name.
				print "$F: unlink(\"$fil\") returned $x.\n" if $V>5;
			} else {
				print STDERR "$F: unlink(\"$fil\") failed ($!)\n" if $V>0;
				$s = int($!);	# Unlink failed.
			}
		} else {
			print STDERR "$0/$F: Can't link \"$fil\" -> \"$bup\" ($!)\n" if $V>5;
			if (rename($fil,$bup)) {	# Try the rename call.
				print "$F: Renamed \"$fil\" -> \"$bup\"\n" if $V>5;
			} else {
				print STDERR "$F: rename(\"$fil\",\"$bup\" failed ($!)\n" if $V>0;
				$s = int($!);	# Link to backup failed.
			}
		}
	} else {
		 print "$F: \"$fil\" at depth $bdepth ignored.\n" if $V>5;
	}
	$bdepth --;
	$exitstat = $s if $s;
	return $s;
}

1;
