#! /usr/bin/env perl

use strict;
use warnings FATAL => qw( all );

use vars qw( $VERSION );
$VERSION = '0.01';

use Getopt::Long qw( GetOptions :config auto_help auto_version );
use Pod::Usage qw( pod2usage );
use IPC::Cmd 0.36 qw( can_run run);
use PS::IPP::Metadata::List qw( parse_md_list );
use PS::IPP::Config 1.01 qw( :standard );


# Tool to seed the summitExp table with an initial exposure, to give the automated summit copy tools a starting point.

my $missing_tools = 0;
my $dsprodls = can_run('dsproductls') or (warn "Can't find dsproductls" and $missing_tools = 1);
my $pztool   = can_run('pztool') or (warn "Can't find pztool" and $missing_tools = 1);

if ($missing_tools != 0) {
    die "Required tools not available";
}

my ($dbname, $dbuser, $dbpass);
my ($datastore_uri, $camera, $telescope);
my ($exp_name);

# Get config information
my $ipprc = PS::IPP::Config->new( ) or die "Could not create config object.\n";
my $siteConfig = $ipprc->{_siteConfig};
$dbuser = metadataLookupStr($ipprc->{_siteConfig}, "DBUSER");
$dbpass = metadataLookupStr($ipprc->{_siteConfig}, "DBPASSWORD");

GetOptions(
    'dbname=s'     => \$dbname,
    'dbuser=s'     => \$dbuser,
    'dbpass=s'     => \$dbpass,
    'exp_name=s'   => \$exp_name,
    ) || pod2usage( 2 );

pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
pod2usage( -msg => "Required options: --dbname", -exitval => 2 )
    unless defined $dbname;
pod2usage( -msg => "Required options: --dbuser", -exitval => 2 )
    unless defined $dbuser;
pod2usage( -msg => "Required options: --dbpass", -exitval => 2 )
    unless defined $dbpass;
pod2usage( -msg => "Required option Last exp_name to skip: --exp_name", -exitval => 2)
    unless defined $exp_name;

my $mdcParser = PS::IPP::Metadata::Config->new;

# Get datastore information
my $pz_cmd = "$pztool -datastore -dbname $dbname";

my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) = 
    run(command => $pz_cmd, verbose => 0);
unless ($success) {
    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    die "Failed to run pztool to determine datastore uri";
}

my $MDlist = $mdcParser->parse(join "", @$stdout_buf) or
    die "Unable to determine datastore uri from pztool output.";
my $metadata = parse_md_list($MDlist);
my $ds_entry = $metadata->[0];

$datastore_uri = $ds_entry->{uri};
$camera        = $ds_entry->{camera};
$telescope     = $ds_entry->{telescope};

# Get all entries after the one we want to ignore

my $ds_cmd = "$dsprodls --uri $datastore_uri --last_fileset $exp_name";
( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) = 
    run(command => $ds_cmd, verbose => 0);
unless ($success) {
    $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    die "Failed to run dsproductls to get results from datastore $datastore_uri\n";
}


my @rows = split /\n/, (join "", @$stdout_buf);

my $have_an_entry = 0;
foreach my $ds_entry (@rows) {
    if ($ds_entry =~ /^#/) { next; }
    if ($have_an_entry == 1) { next; }

    my ($new_exp_uri, $new_exp_name, $new_exp_dateobs, $new_exp_type) = split /\s+/, $ds_entry;
    
    unless ((defined($new_exp_uri))&&(defined($new_exp_name))&&(defined($new_exp_dateobs))&&(defined($new_exp_type))) {
	next;
    }
    unless (($new_exp_uri ne '')&&($new_exp_name ne '')&&($new_exp_dateobs ne '')&&($new_exp_type ne '')) {
	next; 
    }
    $have_an_entry = 1;

    # This is formally done by psTimeFromISO, but this should be fine for seeding
    $new_exp_dateobs =~ s/T/ /;
    $new_exp_dateobs =~ s/Z//;

    my $insert_query = "INSERT INTO summitExp (summit_id, exp_name, camera, telescope, dateobs, exp_type, uri, imfiles, fault, epoch) VALUES (";
    $insert_query   .= " NULL, "; # summit_id
    $insert_query   .= " '$new_exp_name', "; # exp_name
    $insert_query   .= " '$camera', "; # camera
    $insert_query   .= " '$telescope', "; # telescope
    $insert_query   .= " '$new_exp_dateobs', "; # dateobs
    $insert_query   .= " '$new_exp_type', "; # exp_type
    $insert_query   .= " '$new_exp_uri', "; # uri
    $insert_query   .= " NULL, "; # imfiles
    $insert_query   .= " 0, ";    #fault
    $insert_query   .= " NULL); ";  #epoch
    
    print "BEGIN;\n";
    print "$insert_query\n";
    print "COMMIT;\n";
    
}


