#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  nameswap - Interchange the names of two files
#
#SYNOPSIS
#  nameswqp file1 file2
#
#REQUIRES
#
#DESCRIPTION
#
#OPTIONS
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

$| = 1;
$exitstat = 0;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 2;	# Verbose level.

$name1 = shift @ARGV;
$name2 = shift @ARGV;

unless (-f $name1 && -f $name2 ) {
	print STDERR "Usage: nameswqp file1 file2\n" if $V>0;
	exit 1;
}

$tmpx1 = ".tmpx1_$$";
$tmpx2 = ".tmpx2_$$";

# First, link both of the files to a hidden temporary name:
unless (link($name1,$tmpx1)) {
	print STDERR "$P: Can't link \"$name1\" to \"$tmpx1\" [$!]\n";
	exit 2;
}
unless (link($name2,$tmpx2)) {
	print STDERR "$P: Can't link \"$name2\" to \"$tmpx2\" [$!]\n";
	unlink($tmpx1);		# Undo successful first link
	exit 3;
}
# Next, unlink both of the original names, and link the tmp* files to them:
if (unlink($name1)) {			# Erase name1
	if (link($tmpx2,$name1)) {	# Give name1 the content of name2
		print STDERR "$P: \"$name1\" is now \"$name2\"\n" if $V>0;
	} else {
		print STDERR "$P: Can't link \"$tmpx2\" to $name1\" [$!]\n";
		print STDERR "$P: \"$name1\" should still exist as \"$tmpx1\"\n";
		print STDERR "$P: \"$name2\" should still exist as \"$tmpx2\"\n";
		exit 4;
	}
} else {
	print STDERR "$P: Can't link \"$tmpx2\" to $name1\" [$!]\n";
	print STDERR "$P: \"$name1\" should still exist as \"$tmpx1\"\n";
	exit 5;
}
if (unlink($name2)) {
	if (link($tmpx1,$name2)) {
		print STDERR "$P: \"$name2\" is now \"$name1\"\n" if $V>0;
	} else {
		print STDERR "$P: Can't link \"$tmpx1\" to $name2\" [$!]\n";
		print STDERR "$P: \"$name2\" should still exist as \"$tmpx2\"\n";
		exit 6;
	}
} else {
	print STDERR "$P: Can't unlink \"$name2\" [$!]\n" if $V>0;
	print STDERR "$P: \"$name1\" should now be \"$name2\"\n";
	print STDERR "$P: \"$name2\" should still exist as \"$tmpx2\"\n";
	exit 7;
}
print STDERR "$P: \"$name1\" and \"$name2\" should now be interchanged.\n" if $V>1;
unlink($tmpx1);
unlink($tmpx2);

print "$P: Exit with status $exitstat.\n" if $V>1;
exit $exitstat;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
print "$P: Exit with status $exitstat.\n" if $V>1;
exit $exitstat;

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
