#!/usr/bin/perl
#$Id: mail_errors.pl,v 1.2 2018/04/24 06:20:04 sqko Exp $
use strict;
use warnings;
use Date::Parse;
use RFC::Main;
use RFC::Header;
use Fcntl qw(:DEFAULT :flock);
my $file = $homedir.'error.txt';
my $lock = $homedir.'error.lock';
#### Get time one day ago ###
my $time = time - 86400;
$time = localtime($time);
my $date = &getdate($time.' ');
### Locks file access for other processes ###
eval {
    my @list = ();
    sysopen(EFH, $lock, O_WRONLY | O_CREAT) or die "Error: can't open file: $lock";
    flock(EFH, LOCK_SH);
    open MYIN,'<',$file or die "Could not open file $file\n";
    while (<MYIN>)
    {
	push @list,$_ if (&getdate($_) > $date);
    }
    close MYIN;
    flock(EFH, LOCK_UN);
    close(EFH);
    exit unless (@list);
    my $message = join('',@list);
    my @emails = split(/\s*\,\s*/,&get_cv('admin','system_mail_users'));
    for my $email (@emails)
    {
	my $hostname = `/bin/hostname`;
	my $status = &RFC::Main::mail($email,$message,'Errormessages for last 24 hours for '.$hostname.' at '.localtime);
	die "Mail not sent to $email!" unless ($status);
    }
};
if ($@)
{
    die $@;
}


sub getdate($)
{
    my $date = 0;
    my $str = shift;
    if ($str =~ /^(\w+\s+\w+\s+\d+\s+[\d\:]+\s+\d+)\s+/)
    {
	$date = str2time($1);
	$date =~ s/\://g;
    }
    return $date;
}
