#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  restorehst -  Restore the "search" files for a host
#
#SYNOPSIS
#  restorehst [host]..
#
#REQUIRES
	push @INC, '.', 'lib', 'sh';
	require "Backup.pm";
#
#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"} || 1;	# Verbose level.

$bkups = 1;		# Whether to move targer files to backup

for $h (@ARGV) {
	$h =~ s"^.*/"";		# Strip away directory info
	print "$P: Host '$h' ...\n" if $V>1;
	$hst = "hst/$h";
	$lck = "lck/$h";
	$log = "log/$h";
	if (-f ($last = "last/$h")) {
		print "$P: \"$last\" exists.\n" if $V>1;
		system "l2h $h";
	} elsif (-f ($old = "old/$h")) {
		&mv($old,$hst);
	} else {
		print "$P: Host '$h' has no old/$h file.\n" if $V>0;
	}
	if (-f $log) {	# Does the host have a log file?
		print "$P: Unlink '$log'\n" if $V>1;
		unlink($log);
	}
	if (-f $lck) {	# Does the host have a lockfile?
		print "$P: Unlink '$lck'\n" if $V>1;
		unlink($lck);
	}
	system "tail -1 $hst";
}

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

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

sub mv {my $F='mv';
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	local($fr,$to) = @_;
	if (-e $to) {
		if ($bkups) {
			print "$P/$F: Backup '$to'\n" if $V>1;
			&Backup($to) if $bkups;
		}
		print "$P/$F: Link '$fr' -> '$to'\n" if $V>1;
		link($fr,$to);
		print "$P/$F: Unlink '$fr'\n" if $V>1;
		unlink($fr);
	}
}
