#!/usr/bin/perl -w
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
#NAME
#  sshloop - Loop calling ssh
#
#SYNOPSIS
#  sshloop [delay] [host]..
#
#REQUIRES
#
#DESCRIPTION
#  This does "ssh $host" repeatedly, so if the link dies, it is attempted
#  again after the specified delay.
#
#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.
$delay = 5;		# Default delay between ssh attempts (seconds)

if ($ARGV[0] =~ /^\d+$/) {
	$delay = int($ARGV[0]);
	shift @ARGV;
}
print "$P: $delay-sec delay.\n" if $V>2;
STDERR->autoflush(1);
while (1) {
	$cmd = "ssh ". join(' ',@ARGV);
	&dt();
	print "$cymd $hms\t$cmd\n" if $V>1;
	system $cmd;
	$exitstat = $? if $? != 0;
	&dt();
	print "$cymd $hms\tDone.\n" if $V>1;
	for ($d = $delay; $d > 0; --$d) {
		print "$d ... " if $V>1;
		sleep 1;
	}
	print "\n" if $V>1;
}

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

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Get the current data and time.  We leave the integer  timestamp  in #
# $now,  and  the OSI date/time in $cymdhms.  We also leave a shorter #
# date/time string without the century and year in $mdhms. Our return #
# value is $now, the Unix integer timestamp.                          #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

sub dt {
	local($ss,$mm,$hh,$DD,$MM,$CY) = gmtime($now = time);
	$CY += 1900;
	$MM += 1;
	$cymd = sprintf("%04d-%02d-%02d",$CY,$MM,$DD);
	$hms = sprintf('%02d:%02d:%02d',$hh,$mm,$ss); 
#	$cymdhms = "$cymd$hms";		# Not used here
	return $now;
}

