#!/usr/bin/perl -w
# upload images, fetch new scan list.
# N.B. works closely with cdarchive.

# base of operations
$TELHOME = $ENV{TELHOME} or $TELHOME = "/usr/local/telescope";

# access to more goodies
$ENV{PATH} .= ":$TELHOME/bin";

# configure
$user = "ocaas 1dilbert6";
$host = "iro.physics.uiowa.edu";
$pppcmd = "nogppp";
$ftpto = 10;
$stayto = 60;
$sendsls = 1800;
$ftpcmd = "ftp -i -n $host";
$ipfn = "$TELHOME/comm/iro-wmo-ip";
$stayup = "$TELHOME/comm/nog_stayup";
$ftplog = "$TELHOME/archive/logs/ftp.log";

# set of staging areas for making cdroms disk images
@stgdirs = ("/mnt/cdimage/d0",
            "/mnt/cdimage/d1",
            "/mnt/cdimage/d2",
            "/mnt/cdimage/d3",
            "/mnt/cdimage/d4");


# unbuffered stdout
$| = 1;

# exit if already running, besides us
$nnog = `ps ax | grep '[0-9] .*nogchkin *\$' | wc -l`;
if ($nnog > 1) {
    print &timestamp, "Already connected\n";
    exit 0;
}

# do work and stay as long as $stayup is present on far side
do {
    # check stuff
    &checkWork;
    &checkSLS;
    &sendUserLogs;
    &sendWxLog;
    &sendSLS;
    &checkBURNED;

    # check whether to stay connected
    sleep $stayto;
    unlink $stayup;
    &ftp ("get $stayup");
} while (-r $stayup);

# that's it
unlink $ipfn;
&ftp ("delete $ipfn");
print &timestamp, "All finished\n";
system ("jd -t; pppoff");
exit 0;

# check work and all staging areas for urgent things to send
sub checkWork
{
    foreach my $dir ($TELHOME, @stgdirs) {

	# put images and interleave checking for other important stuff
	my $base = "$dir/user/images";
	@ftsh = <$base/*.ft[sh]>; # we handle no files better than sh
	if (@ftsh > 0) {
	    @imf = `fitshdr -P $base/*.ft[sh] | grep PRIORITY= | sort +3 -nr | awk '\$3 <= 0 {print \$1}'`;
	    foreach my $file (@imf) {
		chomp $file;
		&ftp ("put $base/$file $TELHOME/user/images/$file");
		my $newdir = $base; $newdir =~ s#/user/#/archive/#;
		system "mkdir -p $newdir; mv $base/$file $newdir/$file";
		print &timestamp, "Sent $base/$file\n";

		# interleave other stuff
		&checkSLS;
		&sendUserLogs;
		&sendWxLog;
		&sendSLS;
	    }
	}
    }
}

# check for new telrun.sls
sub checkSLS
{
    my $sls = "$TELHOME/archive/telrun/telrun.sls";
    my $slx = $sls; $slx =~ s#sls#new#;
    &ftp ("get $sls $slx");
    if (-s $slx) {
	rename $slx, $sls;
	$slx = $sls; $slx =~ s#sls#sent#;
	&ftp ("rename $sls $slx");
	print &timestamp, "New telrun.sls received\n";
    }
}

# get the BURNED confirm codes and clean their staging area
sub checkBURNED
{
    &ftp ("mget $TELHOME/archive/logs/BURNED.*");

    foreach $BURN (<$TELHOME/archive/logs/BURNED.*>) {
	my $B = $BURN; $B =~ s#.*/##;
	foreach my $stg (@stgdirs) {
	    if (-r "$stg/$B") {
		print &timestamp, "cleaning $stg\n";
		system "rm -fr $stg/archive";
		system "rm -fr $stg/user";
		system "rm -fr $stg/$B";
		last;
	    }
	}
	unlink $BURN;
	&ftp ("del $BURN");
    }
}

# send the telrun.sls file as telrun.now if it has changed in the last hour,
# but not too often.
sub sendSLS
{
    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
				      $atime,$mtime,$ctime,$blksize,$blocks);
    my $sls = "$TELHOME/archive/telrun/telrun.sls";
    my $lastsentfn = "/tmp/lastsentsls";

    # ignore if no telrun file
    return if (! -r $sls);

    # get time telrun file was last changed
    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
		  $atime,$mtime,$ctime,$blksize,$blocks) = stat($sls);
    my $lastchg = $mtime;

    # get time we last sent telrun
    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
		  $atime,$mtime,$ctime,$blksize,$blocks) = stat($lastsentfn);
    my $lastsent = (-r $lastsentfn) ? $mtime : 0;

    # time now
    my $now = time();

    # send if has changed and we have not sent it recently
    if ($lastchg > $lastsent and $now > $lastsent + $sendsls) {
	my $slsnow = $sls;
	$slsnow =~ s/\.sls/.now/;
	open (LS, ">$lastsentfn"); print LS "Hi!"; close LS;	# touch
	&ftp ("put $sls $slsnow");
    }
}

# put user logs -- N.B. they can grow slowly
sub sendUserLogs
{
    foreach my $d ($TELHOME, @stgdirs) {
	my $base = "$d/user/logs";
	foreach my $file (<$base/*.log>) {
	    chomp $file;
	    my $log = $file; $log =~ s#.*/##;
	    &ftp ("append $file $TELHOME/user/logs/$log");
	    my $newd = "$d/archive/userlogs";
	    my $mvfn = $file; $mvfn =~ s#/user/logs/#/archive/userlogs/#;
	    system "mkdir -p $newd; cat $file >> $mvfn; rm $file";
	    print &timestamp, "Sent $file\n";
	}
    }
}

# send wx.log
sub sendWxLog
{
    foreach my $d ($TELHOME, @stgdirs) {
	my $file = "$d/archive/logs/wx.log";
	if (-r $file) {
	    my $wxlog = $file; $wxlog =~ s#.*/##;
	    &ftp ("append $file $TELHOME/archive/logs/wx.log");
	    system "cat $file >> $d/archive/logs/wx.all.log; rm $file";
	    print &timestamp, "Sent $file\n";
	}
    }
}

# connect ftp to host and perform the commands in @_
sub ftp
{
	CMDS: {

	    # be sure ppp is running
	    &pppok or &startppp;

	    # start ftp and save pid in case we need to kill it later.
	    system "date -u >> $ftplog";
	    open FTP, "| $ftpcmd >> $ftplog 2>&1" or die "Can not start ftp\n";
	    my $oldfh = select FTP; $| = 1; select $oldfh;
	    $ftppid = `ps ax | awk '/[0-9] $ftpcmd/ {print \$1;}'` + 0;

	    # log in
	    print FTP "user $user\n";
	    print FTP "binary\n";

	    # send each command
	    foreach $cmd (@_) {
		print &timestamp, "FTP: $cmd\n";	# trace
		print FTP "$cmd\n";
	    }

	    # disconnect
	    print FTP "bye\n";

	    # wait for ftp to finish (good) or ppp to disappear (bad)
	    while (&ftpok) {
		if (!&pppok) {
		    # ppp died -- repeat
		    print &timestamp, "PPP died\n";
		    &ftpkill;
		    close FTP;
		    redo CMDS;
		}
		sleep $ftpto;
	    }

	    close FTP;
	}
}

# return 1 if $ftppid is alive, else 0.
sub ftpok
{
	$ftppid > 0 ? kill (0, $ftppid) : 0;
}

# return 1 if ppp looks ok, else 0
sub pppok
{
	0 + grep /ppp0/, `/sbin/ifconfig`;
}

# start ppp and record ip or die
sub startppp
{
	print &timestamp, "Starting ppp\n";
	system ($pppcmd);
	&pppok or die &timestamp, "Can not start ppp\n";
	system ("/sbin/ifconfig ppp0 | grep 'inet addr' | cut -c21-35 > $ipfn");

	# if don't wait a bit ftp doesn't seem to always work
	sleep 10;
	print &timestamp; system ("echo -n 'IP is '; cat $ipfn");

	&ftp ("put $ipfn");
	print &timestamp, "New ppp session ready\n";
}


# kill off our ftp process
sub ftpkill
{
	print &timestamp, "Killing off stuck ftp pid=$ftppid\n";
	kill (9, $ftppid) if ($ftppid > 0);
	$ftppid = 0;
}

# return a string of the form "YYYYMMDDHHMMSS: "
sub timestamp
{
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);

	sprintf "%04d%02d%02d%02d%02d%02d: ", $year+1900, $mon+1, $mday, $hour,
								    $min, $sec;
}

# For RCS Only -- Do Not Edit
# @(#) $RCSfile: nogchkin,v $ $Date: 2003/04/15 20:48:36 $ $Revision: 1.1.1.1 $ $Name:  $
