#!/bin/perl
#
# Documentation
my $long_doc =
 "check_pass_tables.pl v1.0 - DPB 04-Oct-2007 - beecher\@fnal.gov
  -R        List of runs to check
  -p        This pass version of PROD_PHYSICS_CDF
  -i        This pass_index version of PROD_PHYSICS_CDF
  -n        Table name to check (calibrunlists.calib_table)
  -N        Used set to check
  -I / -E   Show runs (I)ncluding or (E)xcluding the calibration table
  
  -h        Display this help
" ;
my $short_doc = $long_doc ;

use Getopt::Std;
use DBI;
use strict;

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

# Get input from command line
my %opts;
getopts('hIER:n:N:p:i:',\%opts) or die $short_doc;

if ( $opts{h} || ( !$opts{I} && !$opts{E} ) || ($opts{p} && $opts{i}) || (!$opts{n} && !$opts{N}) ) {
	print $long_doc;
	exit
}

# Connect to the database
$ENV{'ORACLE_HOME'} = '/home/cdfsoft/products/oracle_client/v9_2_0_1a/Linux+2';
$ENV{'TNS_ADMIN'} = '/home/cdfsoft/dist/oracle_tnsnames';

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

my $calib_table = "COTHV";
$calib_table = $opts{n} if $opts{n};
chomp($calib_table);

my $pass = "17";
   $pass = $opts{p} if $opts{p}; chomp $pass;
my $pass_index = "0";
   $pass_index = $opts{i} if $opts{i};
   $pass_index = &get_pass_index($dbh,$pass) if $opts{p};
chomp $pass_index;

my $used_set = "PROD_PHYSICS_CDF";
   $used_set = $opts{N} if $opts{N};
chomp $used_set;
open (FIN,"< $opts{R}") or die "Cannot open $opts{R}";

while ( <FIN> ) {
  my $found;
  my $run = $_; chomp($run);
  my $version = &get_latest_version($dbh,$run,$used_set);
     $version = &get_pass_version($dbh,$run,$pass_index) if ( $opts{p} or $opts{i} ) and ( $used_set eq "PROD_PHYSICS_CDF") ;
  my  $jobset = &get_jobset($dbh,$run,$used_set,$version) if $version > 0 ;
  #print "$run $jobset \n"; 
  if ($opts{n}) {
    my $list_tabs = &list_tables($dbh,$jobset);
       $found = grep( /$calib_table/, $list_tabs );
  } else {
       $found = $version > 0;
  }
  
  print "$run\n" if     $found and $opts{I};
  print "$run\n" if not $found and $opts{E};
}
