#!/usr/bin/env perl
##########################################################################
#
# routine: find_split.pl
#
# purpose: Searches for potential q/s split datasets in a science
#          pipeline.  If candidates are found, a confirmation entry
#          must exist in the DADS db table "otfr_special_processing".
#
#          Once a confirmed q/s split is identified, one of the
#          OSFs for the split is triggered for merging.
#
# modification history:
#
#   date    opr     who     reason
# -------- -----  --------  --------------------------------------
# 10/05/00 42246  MSwam     first version
# 08/11/05 53803  MSwam     Replace PATH_FILE_NAME with PATH_BASENAME
# 08/09/10 44712  MSwam     use DBI for database access
# 
##########################################################################
#
# prepend the Perl include variable using all components of PATH
# (this allows us to reuse other OTFR Perl code)
#
$PATH  = $ENV{"PATH"};
@parts = split /:/, $PATH;
while (defined($val = pop(@parts))) {
   if (substr($val,0,1) eq "/") { unshift(@INC, $val)}
}

#
# include these modules
#
require 'printmsg.pl';       # prints a formatted status message
require 'do_dbi_pkg.pl';     # DB access functions
require 'db_osp_processing_steps.pl';  # checks DADS db otfr_special_processing table

# set-up 
#
$all_is_well = 0;
$go_absent = 102;

$path     = $ENV{"PATH_BASENAME"};
$DP_STAGE = $ENV{"DP_STAGE"};
$DP_SEARCH_VALUE = $ENV{"DP_SEARCH_VALUE"};
$DP_MERGE_VALUE  = $ENV{"DP_MERGE_VALUE"};

#
# check for exposures potentially stuck in Data Partitioning 
@out = `osf_test -p $path -c $DP_STAGE -s $DP_SEARCH_VALUE -pr dataset dcf_num | /bin/sort `;
$savestat = $?;
if ($savestat != 0) {
   PrintMsg("E","ERROR: osf_test failed for $path; ecode= $savestat\n");
   exit $go_absent;
}
if (scalar(@out) == 0) {
   # no potential exposures found 
   exit $all_is_well;
}

#
# search for consecutive matching dataset names, up to the 8th character
$prev_test = " ";
$prev_exp = " ";
foreach $exp (@out) {
   $testval = substr($exp,0,8);
   if ($testval eq $prev_test) {
       #
       # verify that otfr_special_processing indicates a merge is needed
       $code = DB_osp_processing_steps(uc($testval));
       if ($code) {
          if ($code =~ /MERGE_REQD/) {
            PrintMsg("W","$code indicated for $prev_exp,$exp");
            #
            # trigger the "higher" of the OSFs (in DCF num order) for merging
            $dset = substr($exp,0,9);
            `osf_update -p $path -f $dset -c $DP_STAGE -s $DP_MERGE_VALUE`;
            if ($? != 0) {
               PrintMsg("E","ERROR: osf_update failed for $path, $dset\n");
            }
            else {
               PrintMsg("I","MERGE has been triggered for $dset");
            }
          }
       }
   }
   $prev_exp = $exp;
   $prev_test = $testval;
}

exit $all_is_well;
