#! /usr/bin/perl -w

use DBI;
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );

my $dbname = 'gpc1';

GetOptions(
    'logs|L'      => \$logs,
    'dbname=s'    => \$dbname,
    );

my $date = shift(@ARGV);
unless(defined($date)) {
    my @time = gmtime;
    $date = sprintf("%4d-%02d-%02d",$time[5] + 1900,$time[4] + 1,$time[3]);
}
print "Date: $date\n";
print "CMD: regtool -checkstatus -date $date -class_id ota33 -dbname gpc1 -simple\n";
chomp(my $bad_exp = `regtool -checkstatus -date $date -class_id ota33 -dbname gpc1 -simple | grep 'stop run' | head -1`);
my @row = split /\s+/, $bad_exp;
if ($#row == 18) {
    print "     exp_name uri registered Nimfile summit_fault download_state newExp_state rawExp_state imfile_state exp_id exp_type dateobs obs_mode object burntool_state class_id summit_class_id is_downloaded is_registered\n";
}
elsif ($#row == -1) {
    print "Everything looks good.\n";
    exit(0);
}
else {
    print "     exp_name registered Nimfile summit_fault download_state newExp_state exp_id exp_type obs_mode burntool_state summit_class_id is_downloaded is_registered\n";
}
print "CheckStatus: $bad_exp\n";
$bad_exp = (split /\s+/, $bad_exp)[0];
print "Exposure: $bad_exp is the current pending exposure.\n";


my $db = init_gpc_db();

my $query = "select exp_name,class_id,burntool_state,data_state,uri,exp_id FROM rawImfile where exp_name = '$bad_exp'";

my $data  = $db->selectall_arrayref( $query );
print "#exp_name   class_id   bt_state   data_state uri\n";
foreach my $row (@{ $data }) {
    my ($exp_name,$class_id,$bt_state,$data_state,$uri,$exp_id) = @{ $row };
    print "$exp_name  $class_id $bt_state $data_state $uri\t";
    if (($bt_state > -10)&&($data_state eq 'check_burntool')) {
	print "#??? regtool -updateprocessedimfile -exp_id $exp_id -class_id $class_id -set_state pending_burntool -dbname gpc1";
    }
    print "\n";
    if ($logs) {
	$reg_log = $uri;
	$reg_log =~ s/$exp_name/${exp_name}.${exp_id}/g;
	$reg_log =~ s/ota/reg.ota/;
	$reg_log =~ s/fits/log/;
	$burn_log = $uri;
	$burn_log =~ s/fits/burn.log/;
	
	print "           REG_LOG: $reg_log\n";
	print "          BURN_LOG: $burn_log\n";
    }
}




sub init_gpc_db {
    use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock';
    my $dbserver = 'ippdb01';
    my $dbuser = 'ippuser';
    my $dbpass = 'ippuser';
    $db = DBI->connect("DBI:mysql:database=${dbname};host=${dbserver};" .
                       "mysql_socket=" . DB_SOCKET(),
                       ${dbuser},${dbpass},
{ RaiseError => 1, AutoCommit => 1}
        ) or die "Unable to connect to database $DBI::errstr\n";
return($db);
}

