#!/export/opt1/perl/bin/perl
#

$ENV{LD_LIBRARY_PATH} .= ":/export/opt1/im/lib";
$ENV{LD_LIBRARY_PATH} .= ":/export/opt1/ghostscript-5.50/lib";
$ENV{LD_LIBRARY_PATH} .= ":/export/opt1/ghostscript-5.50/share/ghostscript/5.50";

$ENV{PATH} .= ":/export/opt1/im/bin:/export/opt1/ghostscript-5.50/bin";
$ENV{DELEGATE_PATH} = "/export/opt1/im/share/ImageMagick";

$ENV{GS_LIB}  = "/usr/openwin/lib/X11/fonts/Type1";
$ENV{GS_LIB} .= ":/usr/openwin/lib/X11/fonts/Type3";
$ENV{GS_LIB} .= ":/usr/openwin/lib/X11/fonts/Type1/outline";
$ENV{GS_LIB} .= ":/export/opt1/ghostscript-5.50/share/ghostscript/fonts";
$ENV{GS_LIB} .= ":/export/opt1/ghostscript-5.50/share/ghostscript/5.50";

$ENV{QWFARS} = "/export/home/matt/dummy_wfars";

use Env qw(USER ORACLE_PASS ORACLE_USER WFD QTEMP QWFARS QINPUT);

$ENV{ORACLE_SID}  = "isc1";
$ENV{TWO_TASK}    = "ISCDB";
$ENV{ORACLE_BASE} = "/oracle1/app/oracle";
$ENV{ORACLE_HOME} = "$ENV{ORACLE_BASE}/product/8.0.5";

$ENV{QTEMP}       = "/var/isctmp";
$ENV{SCHEMA}      = "iscdbadm";
    






# make_temp_dir   COLLECTOR
# oracle_command  REQUESTER
# oracle_error    REQUESTER
# oracle_login    REQUESTER
# oracle_logout   REQUESTER
# oracle_request  REQUESTER
# send_mail       REQUESTER

################################################################

sub make_temp_dir {

    ###################################
    ###                             ###
    ### Creates temporary directory ###
    ###                             ###
    ###################################

    my ($dir); # Output
    my ($curpid, $host); # Internal
    
    $host = `hostname`;
    chop $host;
    
    $curpid = $$;
    
    $dir = "$ENV{QTEMP}/$host$curpid";
    
    while ( -e '$dir' ) {
      $curpid++;
      $dir = "$ENV{QTEMP}/$host$curpid";
    }
    
    system("mkdir $dir") == 0 || die "Failed to make temporary directory\n";
    
    print STDERR "Temp directory = $dir\n";
    
    return ($dir);
    
}

#####################################################

sub oracle_command {

    my ($command) = @_;
    
    ora_do($ENV{LDA}, $command) or oracle_error($ora_errstr);

}

##############################################################################

sub oracle_error {

    print STDOUT "Error!!! $_[0]\n";
    exit(0);

}

############################################################################

sub oracle_login {

    ###############################
    ###                         ###
    ### Connect to Oracle table ###
    ###                         ###
    ###############################
    
    my ($output);
    
    $output = ora_login('', "$ENV{ORACLE_USER}", "$ENV{ORACLE_PASS}" ) or &oracle_error($ora_errstr);
    
    return ($output);
    
}

##############################################################################

sub oracle_logout {

    ###############################
    ###                         ###
    ### Disconnect from Oracle  ###
    ###                         ###
    ###############################
    
    ora_commit($ENV{LDA}) or oracle_error($ora_errstr);
    ora_logoff($ENV{LDA});
    
}

######################################################################


sub oracle_request {

    #################################################
    ###                                           ###
    ### Get output from Oracle DB                 ###
    ###                                           ###
    ### Input: $_[0] = Request (no semicolon)     ###
    ###                                           ###
    ### Output : @request, (output data)          ###
    ###          (Multiple fields joined by '::') ###
    ###                                           ###
    #################################################
    

    my ($request) = @_;
    my ($temp, $outemp, $line);
    my (@ora_output, @phid_data);

    $outemp = ora_open($ENV{LDA},$request) or oracle_error($ora_errstr,$request);

    while ( @phid_data = ora_fetch($outemp) ) {
        foreach $line (@phid_data) {
            if ( ! defined $line ) {$line = "";}
        }
        $temp=join("::",@phid_data);
        push (@ora_output, $temp);
    }

    return @ora_output;

}

##############################################################

sub send_mail {

    #############################################
    ###                                       ###
    ### Sends e-mail messages                 ###
    ###                                       ###
    ### INPUT: $_[0] = Address                ###
    ###        $_[1] = Subject                ###
    ###        $_[2] = Body of message        ###
    ###                                       ###
    ### OUTPUT: E-mail! (hopefully)           ###
    ###                                       ###
    #############################################
    
    #my ($address, $subject, $message) = @_;
    my ($address,  $message) = @_;
 
    open (MAIL,"| /usr/bin/mail '$address'") || &z_mail;
    print MAIL "$message\n";
    close MAIL;
    
    ### Added as problems occurred when too many messages sent at once ###
        
}

### COPIED FROM REQUESTER ###

#DOC#################################################
#DOC
#DOC subroutine date2number
#DOC
#DOC author - M Evans
#DOC date - October 2003
#DOC
#DOC purpose : Converts dates to number of seconds
#DOC
#DOC input : @date - Array of dates, (e.g. '01-11-2000 01:54:54')
#DOC
#DOC output : @number - Array of number (date in secs since reference time)
#DOC
#DOC internal : $date - Used to loop over @date
#DOC            $number - Individual elements of @number
#DOC            $request - SQL request
#DOC
#DOC environment variables : none
#DOC
#DOC calls subroutines : oracle_request (from 'shared.pl')
#DOC
#DOC#################################################

sub date2number {
    
    use strict;
    
    my (@date) = @_;
    my ($date, @number, $number, $request);
    
    foreach $date (@date) {
        
        $request = "select epoch.time('$date') from dual";
        ($number) = oracle_request($request);
        
        push (@number, $number);
        
        
    }
    
    return @number;


}

####################################################

sub inventory_check {

    #############################################################
    ###                                                       ###
    ### Check inventory to see if waveforms are available     ###
    ###                                                       ###
    ### Input: $center, $net, $sta, $chan, $wf_begin, $wf_end ###
    ###                                                       ###
    #############################################################


    use strict;
    
    my ($center, $net, $sta, $chan, $wf_begin, $wf_end) = @_;
    my ($temp, $inv_begin, $inv_end, $out, $request, $sysdate);
    

    ($wf_begin, $wf_end) = date2number($wf_begin, $wf_end);
    
    $request = "select BEGIN, END, SYSDATE from $ENV{INVENTORY} 
                where CENTER = '$center' 
                and NET = '$net' 
                and STA = '$sta' 
                and CHAN = '$chan'
                and PRIMARY_DATA = 'P'";
                
    ($temp) = oracle_request($request);
    
    ($inv_begin, $inv_end, $sysdate) = split(/::/,$temp);
    
    if ($inv_end eq "") { 
        $inv_end = $sysdate;
    }
    
    ($inv_begin, $inv_end) = date2number($inv_begin, $inv_end);
    
    if ($inv_begin eq "") { $out = "U", return $out; } # NO WAVEFORM IN INVENTORY
    
    if ($inv_begin < $wf_begin) {
    
        if ($inv_end > $wf_end) {
            $out = "R"; # REQUEST END EARLIER THAN INVENTORY END
        } elsif ($inv_end eq "") {
            $out = "R"; # NULL INVENTORY END -> CONTINUALLY RECORDING STATION
        } else {
            $out = "U"; # INVENTORY END BEFORE REQUEST END
        }
    
    } else {
        $out = "U"; # REQUEST EARLIER THAN INVENTORY BEGIN
    }
   
    return $out;
    
}

################################################
