

########################################################
# This was stolen from code written and is maintained by:
#    Kirk Bauer <kirk@kaybee.org>
#
########################################################

use POSIX qw(strftime);

# This will pick out only the wanted date from a logfile
# in the standard /var/log/messages format.

# I plan to add a *lot* more date flexibility at a later time...

my $time = time;

$Range = ValueOrDefault($ENV{'LOGWATCH_DATE_RANGE'}, '');
$Debug = ValueOrDefault($ENV{'LOGWATCH_DEBUG'}, 0);

#
# Avoid "Use of uninitialized value" warning messages.
#
sub ValueOrDefault {
    my ($value, $default) = @_;
    return ($value ? $value : $default);
}

#
#Build the regexp for the last n days
#
sub BuildLastNdays {
        my ($last_n_days) = @_;

$SearchDate = "(";
for ( $compteur=0; $compteur<$last_n_days; $compteur++ )
{
$SearchDateTemp = strftime("%d/%b/%Y", localtime($time-($compteur*86400)));

 if ($compteur<($last_n_days-1))
  {
   $SearchDate .= $SearchDateTemp."|";
  }
  else
  {
   $SearchDate .= $SearchDateTemp;
  }
}

$SearchDate .= "):..:..:..";

return ($SearchDate);
}


#
#Return 1 if number 0 otherwise
#
sub isNumber {
my $string = shift @_;
return $string =~ m/^[0-9]+$/;
}



if ((isNumber($Range) eq '1') and $Range > 0)
{
 $SearchDate = BuildLastNdays($Range);
}
if ( $Range eq 'last_month') {
   $SearchDate = strftime("%d/.../%Y:..:..:..", localtime($time-(30*86400)));
}
if ( $Range eq 'yesterday') {
   $SearchDate = strftime("%d/%b/%Y:..:..:..", localtime($time-86400));
}
if ( $Range eq 'last_hour') {
   $SearchDate = strftime("%d/%b/%Y:%H:..:..", localtime($time-3600));
}
elsif ( $Range eq 'today') {
   $SearchDate = strftime("%d/%b/%Y:..:..:..", localtime($time));
}
elsif ( $Range eq 'all') {
   $SearchDate = "..\/...\/....:..:..:..";
}

if ( $Debug > 5 ) {
   print STDERR "DEBUG: Inside ApplyStdDate...\n";
   print STDERR "DEBUG: Range: " . $Range . "\n";
   print STDERR "DEBUG: Looking For: " . $SearchDate . "\n";
}

while (defined($ThisLine = <STDIN>)) {
   if ($ThisLine =~ m/\[$SearchDate/o) {
      print $ThisLine;
   }
}

