#! /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';

# first we need to figure out which runs do not have the S0COTBEAM jobset
use DBI;

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

my @runs;

&get_missing_runs_with_jobset($dbh,'PROD_PHYSICS_SVX',1,'10A',\@runs);

exit unless @runs;

#make sure that we are not looping over runs that will never go into pass 10A
&send_mail('tvine@fnal.gov,smalik@fnal.gov','too many runs','merge_svx.pl') if  @runs > 100;



# loop through the runs and skip those that are already merged

foreach my $run ( @runs ) 
{
  my $svx = &get_jobset($dbh,$run,'PROD_PHYSICS_SVX',1); 

  my $latest_version = &get_latest_version($dbh,$run,'PROD_PHYSICS_CDF');
  my $latest_jobset  = &get_jobset($dbh,$run,'PROD_PHYSICS_CDF',$latest_version);

  # check that is has not been merged alrady (ie only if diff_tables returns a non-zero string)
  # and that it has a version of PROD_PHYSICS_CDF already

  next unless $latest_version && &diff_tables($dbh,$svx,$latest_jobset);

  print "********* ".localtime().": Found new run $run missing PROD_PHYSICS_SVX *****************\n";
  print "merging run $run:\n";


  print &db_set_merge($run,'PROD_PHYSICS_CDF',$svx, "test" );
  print &db_set_merge($run,'PROD_PHYSICS_CDF',$svx, "write" );
}


