#!/usr/local/bin/perl
# 
# $Header: archivealertlog.pl 13-nov-2006.07:05:21 ganessub Exp $
#
# archivealertlog.pl
# 
# Copyright (c) 2006, Oracle. All rights reserved.  
#
#    NAME
#      archivealertlog.pl - Retrieves alert log file content for archival.
#
#    DESCRIPTION
#      Given  Oracle alert log file
#      archivealertlog retrieves the content of the alert log file which are older
#      than given number of days.
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    ganessub    11/13/06 - Bug 5622272 fix.
#    ganessub    07/05/06 - 
#    armaity     06/25/06 - 
#    ganessub    03/29/06 - creation.
# 
#

use strict;
use Time::Local;
use HTTP::Date;
use DateManip;
use Fcntl qw (:flock);

require "alertlog_util.pl";
require "archivepurge_util.pl";

# Command Line Arguments
my $argnum = @ARGV;

my $logFile = shift(@ARGV);
my $archiveAge = shift(@ARGV);   # number of days older need to be archived
my $destfile   = shift(@ARGV);
my $destusername   = shift(@ARGV);
my $destpassword   = shift(@ARGV);
my $desthost   = shift(@ARGV);
my $sourcehost   = shift(@ARGV);
my $purgeFlag  = shift(@ARGV);
# End Arguments
# Check if timezone exist if not set to UTC as it is required by DateManip module.
my $timez = $ENV{"TZ"};
print "Host Time Zone is : $timez\n";

if ( $timez eq '') {
   print "Warning:Local Timezone is not set on this host, hence UTC is assumed as a timezone.";
   print "        Set TZ environment variable if you want correct timezone.";
   &Date_Init("TZ=UTC");
}

my $stime;      # start time filter
my $etime;      # end time filter

my $err;
my $ftp;
my $ftpfd;

my $localtstamp =  getlocaltimestamp();
$destfile = $destfile.".".$localtstamp;

# set start time as zero 
  $stime = 0;

# compute the end time 
my  $archiveAgeStr = "- ".$archiveAge . " days";
my  $calcdate = DateManip::DateCalc("today",$archiveAgeStr,\$err);
my  $dispdate = DateManip::UnixDate($calcdate,"%b %e %Y");
  print "Retriving contents older than $dispdate...";
my  $syear   = DateManip::UnixDate($calcdate,"%Y");
my  $smonth  = DateManip::UnixDate($calcdate,"%m");
    $smonth  = $smonth - 1;
my  $sday    = DateManip::UnixDate($calcdate,"%d");
    $sday     = $sday - 1;
my  $shour   = 23; 
my  $smin    = 59; 
my  $ssec    = 0; 
  $etime = $ssec.":".$smin.":".$shour.":".$sday.":".$smonth.":".$syear;

if (! -e $logFile) {
  print "em_archivealertlogError01:\n Alert Log file($logFile) does not exist,archive operation failed. ";
  exit 1;
}

if(!open(FH, "$logFile"))  
{
    print "em_archiveAlertLogError2:Unable to open:$logFile\n, Archive operation failed.";
    exit 1;
}

if ($sourcehost eq $desthost)
{
  if(!open(FH2, ">$destfile"))  
  {
    print "em_archiveAlertLogError2:Unable to create:$destfile\n, Archive operation failed.";
    exit 1;
  }
}
else
{
     # Create a new Net::FTP object, changing the
     # timeout to 60 seconds
     $ftp = Net::FTP->new($desthost, Timeout => 60)
               or die "Could not connect to $desthost. Archive operation aborted.";
     $ftp->login($destusername,$destpassword)
      or die "Can't login ($desthost):" . $ftp->message;
     # Send the STOR command to the destination server 	
     # and obtain a file descriptor  
     $ftpfd = $ftp->stor($destfile) or die "Cannot store '$destfile': $!";  
}

my $startPoint = 0; 


if(!seek(FH, $startPoint, 0))  
{
    print "em_archiveAlertLogError3: Error while reading $logFile\n,Archive operation failed.";
    exit 1;
}

my $bufferSize = 1000; # size of read buffer in bytes
my $record;

if ( (!defined($stime) &&  !defined($etime)) || ($stime eq '0' && $etime eq '0'))
{
    while(<FH>)
    {
        #read(FH, $record, $bufferSize) || die "can't read $logFile: $!";
        if(!read(FH, $record, $bufferSize))  
        {
            print  "em_archiveAlertLogError4: Error while reading $logFile\n";
            exit 1;
        }    
       if ($sourcehost eq $desthost)
       {
              print FH2 $record;
       }
       else
       {
             $ftpfd->write($record, length $record);  
       }
    }
}
else
{
    my $secs;
    my $found=0;

    # start time
    my $stimesec;
    if ($stime eq '0')
    {
        $stimesec = 0;
    }
    else
    {
        my @startlist=split(':', $stime);
        $stimesec = timelocal(@startlist);
    }        
    
    # end time
    my $etimesec;
    if ($etime eq '0')
    {
        $etimesec = 0;
    }
    else
    {
        my @endlist=split(':', $etime);
        $etimesec = timelocal(@endlist);
    }    

    while(<FH>)
    {
        $record = $_;    
        
        if ($found == 0 ||  $etimesec != 0)
        {
            $secs = str2time($record);   
    
            if (defined $secs)
            {
                if ($secs >= $stimesec && ($secs <= $etimesec || $etimesec == 0))
                {        
                    $found = 1;
                }
                elsif ($secs > $etimesec && $etimesec != 0)
                {
                    last;
                }        
            }                  
        }           
    
        if ($found == 1)
        {         
       #     print FH2  "$record";
         if ($sourcehost eq $desthost)
         {
              print FH2 $record;
         }
         else
         {
             $ftpfd->write($record, length $record);  
         }
        }  

    }     
}

         if ($sourcehost eq $desthost)
         {
           close FH2;  
         }
         else
         {
            $ftpfd->quit() or die 
             "Can't close file in the destination host: $!";  
            $ftp->quit() or die 
             "Can't quit ftp connections: $!";  
         }

close FH;  
print "\nAlert log content is stored as $destfile in the destination host.";
if ($purgeFlag eq "true")
{

 purge_alert_log($logFile,$archiveAge);

}
