#!/usr/bin/env perl
#----------------------------------------------------------------------------
#
# Name:  mscxtr_get_filetime
#
#    Retrieves the replan time for a MSC file.
#
# Usage:
#	>mscxtr_get_filetime.pl pod_name
#          where pod_name must match a MSC dataset_name in file_times table. 
#
#	Note that the following environment variables are required:
#       DSQUERY and OPUS_DB.
#
# History:
# Date     OPR      Who         Reason
# -------- -------- ----------  ---------------------------------------------
# original ???
# 03/24/10 64274    MSwam       Replace ST_DBlib with DBI
# 06/30/10 64432    MSwam       Use single quotes for SQLServer
#----------------------------------------------------------------------------
unshift @INC, ( split /:/, $ENV{PATH} );
require 'do_dbi_pkg.pl';        # run queries that return records

# set exit status
$EXIT_SUCCESS=    0;
$EXIT_FAILURE=    1;

#check for arguments
    $num_arg = scalar @ARGV;

    if ($num_arg > 1) {
        $POD_FILE = uc($ARGV[0]);
        $FIELD_NAME = lc($ARGV[1]);
    } else {
       PrintMsg ("E","Missing argument.");
       exit( $EXIT_FAILURE);
    } 

# get the external variables
    $DSQUERY=         $ENV{"DSQUERY"};
    $OPUS_DB=         lc($ENV{"OPUS_DB"});

#---------------------------------------------------------------------
# check input
#---------------------------------------------------------------------


    if (defined( $DSQUERY) && defined( $OPUS_DB) ) {
      $db = DoDBIopen( $DSQUERY, $OPUS_DB, $EXIT_FAILURE);
    } else {
      PrintMsg ("F","ENV variables DSQUERY and OPUS_DB must be defined.");
      exit( $EXIT_FAILURE);
    }
#---------------------------------------------------------------------
# query file_times for  MSC replan time.
#---------------------------------------------------------------------
$query = <<"EOQ";
SELECT $FIELD_NAME
FROM file_times
WHERE dataset_name = '$POD_FILE' and archclass = 'MSC'
EOQ
    @msc_time = DoDBIselect( $db, $query );
    # convert yyyydddhhmmss to yyyy.ddd:hh:mm:ss.00
    $msc_time[0]  =~s/^(....)(...)(..)(..)(..)/$1\.$2:$3:$4:$5\.00/;
    print("$msc_time[0]\n");
    DoDBIclose($db);
    exit( $EXIT_SUCCESS);

#---------------------------------------------------------------------
# end of main procedure -- subroutines follow
#---------------------------------------------------------------------
sub PrintMsg
{
    my ($type,$msg) = @_;
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
    my $date;

    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
    $year   += 1900;
#----  Perl day of year is zero based !!
    $yday++; 
    $date = sprintf("%4d%03d%02d%02d%02d",$year,$yday,$hour,$min,$sec);
    print "$date-$type-$msg\n";
}
