#!/usr/bin/env perl
#----------------------------------------------------------------------------
#
# Name: orphan_clean_monitor
#
# This script is designed to be run under XPOLL using a time trigger.  
# 
# This perl script verifies that the input environment variables are OK.
#
#	Note that the following environment variables are always required:
#       OPUS_SERVER, OPUS_DB, PATH_BASENAME, ORPHAN_DATA_ID, ORPHAN_CLEAN_STAGE,
#       ORPHAN_HOLD_STATUS, and ORPHAN_WAIT_STATUS.
#
# History:
# Date     OPR      Who       Reason
# -------- -------- --------- ---------------------------------------------
# 01/31/03 47437    Baum      Initial version
# 08/11/05 53803    MSwam     Replace PATH_FILE_NAME with PATH_BASENAME
# 03/24/10 64274    MSwam     Replace ST_DBlib with DBI
# 06/30/10 64432    MSwam     Use single quotes for SQLServer
# 09/18/12 72255    Sherbert  get rid of DSQUERY
#----------------------------------------------------------------------------
# set up external routines
unshift @INC,(split /:/, $ENV{PATH});
require 'printmsg.pl';       # prints a formatted status message
require 'do_dbi_pkg.pl';         # run query returning only record count

#---------------------------------------------------------------------
#specify exit status values
#---------------------------------------------------------------------
    $PROCESS_SUCCESS = 0;   # exit status will be ignored by XPOLL
    $PROCESS_ABORT   = 101; # kills process because of ENV errors
    PrintMsg ("I","--- start --- Orphan cleanup monitor -------");

#---------------------------------------------------------------------
# check pipeline variables 
#---------------------------------------------------------------------
    $OPUS_SERVER=       $ENV{"OPUS_SERVER"};
    $OPUS_DB=           lc($ENV{"OPUS_DB"});
    $path_file_name=    $ENV{"PATH_BASENAME"};
    $data_id=           $ENV{"ORPHAN_DATA_ID"};
    $stage=             uc($ENV{"ORPHAN_CLEAN_STAGE"});
    $hold=              lc($ENV{"ORPHAN_HOLD_STATUS"});
    $wait=              lc($ENV{"ORPHAN_WAIT_STATUS"}); 
    $archclass=         uc($ENV{"ASN_ARCHCLASS"}); 

    if ((!defined($OPUS_SERVER))         ||
        (!defined($OPUS_DB))         || 
	(!defined($path_file_name))  ||
	(!defined($data_id))         ||
	(!defined($stage))           ||
	(!defined($hold))            ||
	(!defined($wait))            ||
	(!defined($archclass)))
    {
       PrintMsg("E",
	  "At least one of the following ENV variables is not present:");
       PrintMsg("E",
	  "  OPUS_SERVER, OPUS_DB, PATH_BASENAME, ASN_ARCHCLASS, ORPHAN_DATA_ID,");
       PrintMsg("E",
	  "  ORPHAN_CLEAN_STAGE, ORPHAN_HOLD_STATUS, or ORPHAN_WAIT_STATUS.");
       PrintMsg("E","Killing the process.");
       exit( $PROCESS_ABORT);
    }
    $osf_test_cmd = 
      "osf_test -p $path_file_name -t $data_id -c $stage -s $hold -pr dataset"; 
    @held_osfs =`$osf_test_cmd`;
    if ($?) {
        PrintMsg ("W","osf_test failure - orphans not checked");
        exit( $PROCESS_SUCCESS);
    }
    $num_osfs = scalar @held_osfs;
    if ($num_osfs == 0) {
        PrintMsg ("I","No held orphans found in $path_file_name.");
    } else {
        $db = DoDBIopen( $OPUS_SERVER, $OPUS_DB, $PROCESS_SUCCESS);

	# strip off .path from path name for dads_archive record
	$path_file = $path_file_name;
	if ($path_file_name =~m/\.path/) {
	    $path_file =~s/\.path//;  # replace .path will null string
	} 
        for (@held_osfs) {
            chomp;   # remove newline
            $dataset = $_;
            $uc_dataset = uc($dataset);
            PrintMsg ("I","Checking held orphan: $dataset");
            if (Archive_Complete($uc_dataset,$db)) {
	       $osf_upd_cmd = "osf_update -p $path_file_name -t $data_id ".
	           "-f $dataset -c $stage -s $wait";
		PrintMsg("I","Running: $osf_upd_cmd");   
               `$osf_upd_cmd`;
               if ($?) {
                   PrintMsg ("W","osf_update failure - orphan not cleaned");
	       }
	   }
        }
        DoDBIclose($db);
    }
    PrintMsg ("I","---  end  --- Orphan cleanup monitor -------");
    exit( $PROCESS_SUCCESS);
#---------------------------------------------------------------------
# end of main procedure -- subroutines follow
#---------------------------------------------------------------------
sub Archive_Complete
{
#   get response value from most recently archived association dataset 
#   in the desired archclass and path 

    # begin
    my ($rootname, $db) = @_;
    my $program_id = substr($rootname,1,3);
    my $obset_id   = substr($rootname,4,2);
    my $ob_number  = substr($rootname,6,2);
    my $query = <<"EOQ";
SELECT d.response, a.association_id
FROM dads_archive d, asn_members a
WHERE a.program_id='$program_id' and a.obset_id='$obset_id'
 and a.member_num = '$ob_number' and d.archclass='$archclass' and
 d.dataset_name=a.association_id and d.path='$path_file' and
 d.reqdate = (SELECT max(reqdate) FROM dads_archive
              WHERE archclass='$archclass' and dataset_name=a.association_id
	        and path='$path_file')
EOQ

    my @in_record = DoDBIselect($db, $query);
    my $response = $in_record[0];
    my $asn_id   = $in_record[1];
    if (defined( $response)) {
        PrintMsg("I", "Found dads_archive response $response for $asn_id.");
        if ($response eq "OK") {
	    return(1);
	} else {
	    return(0);
	}
    } else {
        PrintMsg( "I", "No dads_archive record for orphan association.");
        return(0);    
    }
}
