#!/usr/local/bin/perl
# 
# $Header: textIndexLogViewer.pl 03-jul-2006.01:58:39 ganessub Exp $
#
# textIndexLogViewer.pl
# 
# Copyright (c) 2006, Oracle. All rights reserved.  
#
#    NAME
#      textIndexLogViewer.pl - <one-line expansion of the name>
#
#    DESCRIPTION
#      This script is used to retrieve the given text log file content.
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    ganessub    06/27/06 - Creation
# 
use strict;
use Time::Local;
use HTTP::Date;

require "alertlog_util.pl";

# Command Line Arguments
my $argnum = @ARGV;

my $logFile = shift(@ARGV);
my $sizeToView = shift(@ARGV); # The last <sizeToView> bytes to view

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

if ($argnum > 2)
{
    $stime=shift(@ARGV);
    $etime=shift(@ARGV);
}
# End Arguments


if(!open(FH, "$logFile"))  
{
    print "$logFile does not exist.\n";
    exit 0;
}


seek(FH,0,2);  # go directly to EOF

my $fileSize = tell(FH);
my $startPoint = $fileSize - $sizeToView;

if($startPoint < 0)
{
    $startPoint = 0; 
}

if(!seek(FH, $startPoint, 0))  
{
    print "Could not read $logFile\n";
    exit 0;
}

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 "Error occured while reading $logFile\n";
            exit 0;
        }    
        print $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 "$record";
        }  
    }     
}

close FH;  
