#! /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{'TNS_ADMIN'} = '/home/cdfsoft/dist/oracle_tnsnames';


use DBI;

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

# first we need to figure out which runs are not in pass 17A but are in pass 10


# get the pass indices
my $pass10_svx = &get_pass_index($dbh,'10','PAD_PHYSICS_SVXBEAM'); 
my $pass10_cot = &get_pass_index($dbh,'10','PAD_PHYSICS_COTBEAM'); 
my $pass17A    = &get_pass_index($dbh,'17A'); 
my $pass10A    = &get_pass_index($dbh,'10A'); 



my $sql = 
'select lorun from passcalibs
where pass_index = ?
  and lorun >  228100
  and lorun in (select lorun from passcalibs where pass_index = ? )
  and lorun not in (select lorun from passcalibs where pass_index = ? )
order by lorun'; 

# and lorun in (select lorun from passcalibs where pass_index = ? )

my $sth = $dbh->prepare($sql);
$sth->execute($pass10_cot,$pass10_svx,$pass17A);

my @runs;

while (my $row = $sth->fetchrow) { push @runs, $row}

exit unless @runs;

my %pass_runs;

#loop through the runs and create PROD_PHYSICS_CDF
foreach my $run ( @runs ) 
{

  print "********* ".localtime().": Found new run $run not in pass 17A.  Merging run....\n";

  # now we need to get the jobsets to be merged

  my $base_version = &get_pass_version($dbh,$run,$pass10A);
  my $svx_version  = &get_pass_version($dbh,$run,$pass10_svx);
  my $cot_version  = &get_pass_version($dbh,$run,$pass10_cot);

  my $base_jobset = &get_jobset($dbh,$run,'PROD_PHYSICS_CDF',$base_version);
  my $svx_jobset  = &get_jobset($dbh,$run,'PAD_PHYSICS_SVXBEAM',$svx_version);
  my $cot_jobset  = &get_jobset($dbh,$run,'PAD_PHYSICS_COTBEAM',$cot_version);


  print &db_set_merge($run,$base_jobset,"$svx_jobset $cot_jobset", 'test' );
  print &db_set_merge($run,$base_jobset,"$svx_jobset $cot_jobset", 'write' );


  $pass_runs{$run} = &get_latest_version($dbh,$run,'PROD_PHYSICS_CDF'); 
}


# add all of the recently merged runs into 17A

print &fill_pass($pass17A,\%pass_runs,'write');


#__________________________________________________________________
