#!/bin/env perl

# query the root of the datastore on conductor to find the latest gpc1 exposure.
# Print out it's name and the dateobs (actually registration time)
# along with the current time and time since the last exposure.

use strict;
use warnings;

my $setlast;

my $camera = 'gpc1';
while (@ARGV) {
    if ($ARGV[0] eq '--setlast') {
        $setlast = 1;
        shift;
    } elsif (($ARGV[0] eq '--camera') or ($ARGV[0] eq '-c')) {
        shift;
        $camera = shift;
    } else {
        die "don't know argument $ARGV[0]\nusage: $0 [--camera <camera> --setlast]\n";
    }
}

my $out;
if ($camera eq 'gpc1') {
    $out = `dsrootls --uri http://conductor.ifa.hawaii.edu/ds/index.txt`;
} elsif ($camera eq 'gpc2')  {
    $out = `dsrootls --uri http://dsmaster.ps2/ds/index.txt`;
## old tunnel 201809xx MEH    
#    $out = `dsrootls --uri http://conductor.ps2.ifa.hawaii.edu:8080/ds/index.txt`;
} else {
    die "don't know data store address for camera $camera\n";
}

die "dsrootls returned no output" if !$out;
my @lines = split "^", $out;

die "dsrootls returned less than 2 lines" if @lines < 2;
# first line is the header, second is the output
my ($uri, $product, $exp_name, $dateobs);
for (my $i = 1; $i < scalar @lines; $i++) {
    ($uri, $product, $exp_name, $dateobs) = split " ", $lines[$i];
    last if $product eq $camera;
}

die "can't find status line for $camera\n" unless $product;

# get the current time
my ($sec, $min, $hour, $mday, $month, $year) = gmtime;

# convert to usual values
$year += 1900;
$month += 1;

my $date = sprintf "%4d-%02d-%02d", $year, $month, $mday;
my $time = sprintf "%02d:%02d:%02d", $hour, $min, $sec;


print "Current Time $date $time\n";

# split the datobs which is YYYY-MM-DDTHH:MMSSZ
# into date and time
my ($d, $t) = $dateobs =~ m/(.*)T(.*)Z/;

# now split the date
my ($obs_year, $obs_mon, $obs_mday) = split "-", $d;

# if dateobs was in current month compute time since exposure
# this is easy enough. There is no point trying to handle changes 
# in month
# there's probably a nice perl module I could use for this but...

my $delta = "";

if (($obs_year == $year) and ($obs_mon == $month)) {
    my ($h, $m, $s) = split ":", $t;
    my $ds = $sec - $s;
    if ($ds < 0) {
        $ds += 60;
        $m  += 1;
    }
    my $dm = $min - $m;
    if ($dm < 0) {
        $dm += 60;
        $h += 1;
    }
    my $dh = $hour - $h;
    $dh += ($mday - $obs_mday) * 24;
    $delta = sprintf "%02d:%02d:%02d ago", $dh, $dm, $ds;
}

print "$exp_name  $d $t $delta\n";


if ($setlast) {
    # update the last fileset seen value that the program
    # pls uses ("product list" actually "list gpc1 product")
    my $home = $ENV{HOME};
    my $fn = "$home/.last_${camera}_fileset";
    open OUT, ">>$fn" or die "can't open $fn";
    print OUT "$exp_name\n";
    close OUT;
}
