#! /cdf/scratch/cdfopr/cdfcalib/products/bin/perl

use strict;
use lib '/cdf/scratch/cdfopr/cdfcalib/perl_libs';
require "db_queries.pl";

#$ENV{'ORACLE_HOME'} = '/home/cdfsoft/products/oracle_client/v9_2_0_1a/Linux+2';
$ENV{'ORACLE_HOME'} = $ENV{'CDFSOFT2_DIR'}.'/../../../products/oracle_client/v9_2_0_1a/Linux+2';
#$ENV{'TNS_ADMIN'} = '/home/cdfsoft/dist/oracle_tnsnames';
$ENV{'TNS_ADMIN'} = $ENV{'CDFSOFT2_DIR'}.'/../../oracle_tnsnames';

use DBI;

my $dbh = DBI->connect('dbi:Oracle:cdfonprd','cdf_reader','reader') 
	or die "Error connecting $DBI::errstr\n";

my $svx_txt = '';
my $cot_txt = '';
my $beamlines_txt = '';
my $calib_txt = '';


my $run = $ARGV[0];
printf("Examining run $run\n");

{

    my @passes = ("10A","17A","17");
    my @process = ("PAD_PHYSICS_SVXBEAM","PAD_PHYSICS_COTBEAM","PROD_PHYSICS_SVX","PROD_PHYSICS_COT","PROD_PHYSICS_CDF","");
    
    my $pass;
    my $proc;
    foreach $pass (@passes)
    {
	my $goodp = &check_pass( $dbh, $run, $pass);
	printf("[$pass $goodp] ");
    }
    
    foreach $proc (@process)
    {
	my $txt = &check_process( $dbh, $run,$proc);
	printf("{$proc $txt}");
	
	
    }
    printf("\n");
}


$dbh->disconnect;

exit;

sub check_pass
{
    #i) db handle ii) run iii) pass name vi) jobset name v) time offset in hours 
    
    # this checks that a run is not in a pass AND (if specified) is missing a jobset
    # returns a string if missing
    
    my ( $dbh, $run, $pass ) = @_;

    my $pass_index = &get_pass_index( $dbh, $pass );

    my $sth = $dbh->prepare( "select lorun from passcalibs 
                          where lorun = ? and pass_index = ?" );

    $sth->execute( $run, $pass_index );
    if ( $sth->fetchrow ) { return 1 };
    return 0;
}

sub check_process
{
    
    my ( $dbh, $run, $process_name ) = @_;
    
    
    my $latest = &get_latest_version( $dbh, $run, $process_name );

    return $latest;
}
