#!/usr/bin/env perl
#----------------------------------------------------------------------------
#
# Name: set_ingest_cleanup.pl
#
# This is an interactive tool that updates the ingest_cleanup table which
# provides the clean delay values used by CLNING tasks when datasets are marked
# ready for cleanup. The tool can also be used to add new records to this table.
#
# Account requirements:
#
# The account using this progrom must use the opus_login.csh script
# to set up the required ENV variables for this script.
#
# Command Usage: (see $usage definition below)
#
#  Return values:
#     0 - success
#     1 - failure
#
# ENV variables:
#     DSQUERY is the database server name
#     ARCH_DB is the DADS database name used by the Ingest pipeline
#    
# History:
# Date     OPR      Who         Reason
# -------- -------- ----------  ---------------------------------------------
# 05/28/04 50937    Baum        Initial code
# 03/25/10 64274    MSwam       Replace ST_DBlib with DBI
# 06/30/10 64432    MSwam     Use single quotes for SQLServer
#----------------------------------------------------------------------------
# set up external routines
unshift @INC,(split /:/, $ENV{PATH});
require 'do_dbi_pkg.pl';            # run query returning only record count

# begin 
    #specify exit status values
    $EXIT_FAILURE =      1;   # exit status for errors
    $EXIT_SUCCESS =      0;   # exit status for success

# check ENV variables used for queries
    $DSQUERY         = $ENV{"DSQUERY"};
    $ARCH_DB         = $ENV{"ARCH_DB"};
    if (!defined($DSQUERY) || !defined($ARCH_DB)) {
       print "Missing ENV variables: DSQUERY or ARCH_DB.\n";
       exit( $EXIT_FAILURE);
    }
# define command usage
    $usage = <<"EOM";    
Usage:
>set_ingest_cleanup.pl <delay_days> [-new] <archclass-1> <archclass-2> ...

   where the <delay_days> is an integer, the -new argument is optional, and at
   least one archive class in a list separated by blanks is required. If
   the -new option is used an existing archive class will not be updated but
   its current value will be reported. The letter case of the archive class 
   names does not matter.
  
  Examples:
    To set the clean delay to 7 days for POD and EDT datasets, use:
        >set_ingest_cleanup.pl 7 pod edt

    To create a new entry for archive class XYZ in the ingest_cleanup table
    with a delay of 24 days, use: 
        >set_ingest_cleanup.pl 24 -new xyz
      
EOM
    # start argument checks
    $num_args = scalar @ARGV;

    if ($num_args < 2) {    
        print $usage;
        exit ($EXIT_FAILURE);
    }
    # verify first argument is an integer
    $delay_days = shift @ARGV;
    
    if ( !($delay_days =~m/^\d+$/)) {
        print "Error - first argument must be positive integer.\n $usage";
        exit ($EXIT_FAILURE);        
    }    
    #check for "new" option
    if ($ARGV[0] eq "-new") {
        $new_class = 1;
        shift @ARGV
    } else {
        $new_class = 0;
    }
    if (!(scalar @ARGV)) {
        print "Error - too few arguments.\n $usage";
        exit ($EXIT_FAILURE);        
    }
    # validate all class names which must be exactly three characters
    foreach $archive_class (@ARGV) {
       if ( !($archive_class =~m/^\w\w\w$/)) {
          print "Error - argument <$archive_class> must be 3 letters.\n $usage";
          exit ($EXIT_FAILURE);        
       }
    }
    # open database for queries
    $db = DoDBIopen( $DSQUERY, $ARCH_DB, $EXIT_FAILURE);
    
    # process all class names
    foreach $archive_class (@ARGV) {
       $archive_class = uc($archive_class);
       $old_delay = get_old_delay_days(); 
       
       if ($new_class ) {
          if ($old_delay < 0) {
             print "Creating record for $archive_class with delay days set to ".
                "$delay_days.\n"; 
             insert_new_cleanup_record();
          } else {
             print "Record for $archive_class already exists with delay ".
                "$old_delay.\n"; 
          }
       } else { 
          if ($old_delay < 0) {
            ErrorExit("No record for archive class <$archive_class>");
          } elsif ($old_delay == $delay_days) {
             print "No change for $archive_class - $old_delay delay days.\n"; 
          } else {   
             print "Updating class $archive_class: changing delay days ".
                "from $old_delay to $delay_days.\n"; 
             update_old_cleanup_record();
          }             
       }
    }
    DoDBIclose($db);
    undef $db;     
    exit( $EXIT_SUCCESS);  
#----------------------------------------------------------------------------
sub ErrorExit {   
   # one argument - the error message without newline
   # exit the script with the error condition after closing the $db database
   # objest and writing the error message to the log file.
   
   my ($msg) = @_;
   if (defined($db)) {
      DoDBIclose($db);
   }
   print "Error - ".$msg."\n";
   exit ( $EXIT_FAILURE);
}
#-----------------------------------------------------------------------------
sub get_old_delay_days {  # no args; use global variables
   # check for existing record 

   my $query =<<"EOQ";
SELECT icl_clean_delay_days  FROM ingest_cleanup
WHERE  icl_archive_class = '$archive_class'
EOQ
   my (@delay) = DoDBIselect( $db, $query);

   if (!defined(@delay)) {
      print "Cannot query ingest_cleanup.\n";
      return -1;
   }
   $delay[0];  # return delay days
} 
#-----------------------------------------------------------------------------
sub insert_new_cleanup_record {   # no args; use global variables

   my $query =<<"EOQ";
INSERT INTO ingest_cleanup (icl_archive_class, icl_clean_delay_days) 
VALUES ('$archive_class', $delay_days)
EOQ

   my $rec_count = DoDBI( $db, $query);
   
   if ($rec_count == 0) {
      ErrorExit("No record inserted for query:\n$query");
   }             
} 
#-----------------------------------------------------------------------------
sub update_old_cleanup_record {   # no args; use global variables

   $query =<<"EOQ";
UPDATE ingest_cleanup SET icl_clean_delay_days = $delay_days
WHERE icl_archive_class = '$archive_class'
EOQ

   my $rec_count = DoDBI( $db, $query);
   
   if ($rec_count == 0) {
      ErrorExit("No record updated for query:\n$query");
   }             
}
