#!/usr/bin/perl

=begin -------------------------------------------------------------------------
searches cron.log entries for errors -> admin email; only looks for current date
which is in yyyy-mm-dd format so uses DateTime::Format::MySQL for simplicity
=cut ---------------------------------------------------------------------------

use strict;
use warnings;

my $JUST_TESTING = 0; # dumps result to console - no email

################################################################################
my @recipients = qw( raj );
my $src = '/home/raj/crons/cron.log';
################################################################################

use lib '/home/raj/perl5/lib/perl5';

use IO::All;
use DateTime;
use Data::Dumper;
use DateTime::Format::MySQL;

use FindBin qw($Bin); # warn $Bin;
use lib "$Bin/../../../lib";
use LIMS::Local::ScriptHelpers;

my $tools = LIMS::Local::ScriptHelpers->new();
$tools->test_only($JUST_TESTING);

my @log = io($src)->slurp; # warn Dumper \@log;

my $today = DateTime->today;

# reverse so most recent entry 1st:
ROW: for (reverse @log) {
	my ($date) = $_ =~ /\[(\d{4}-\d{2}-\d{2}) \d{2}\:\d{2}\:\d{2}\]/; # warn $date;
	
	unless ($date) { # will be error 
		mail_admin($_);
		next ROW;
	}
	
    my $dt = DateTime::Format::MySQL->parse_date($date);
	# delta_days() returns zero for current date, otherwise positive integer:
	last ROW if $dt->delta_days($today)->delta_days;
}

sub mail_admin {
	my $str = shift; # warn $str;

	my %args = (
		subject => '*** CRON LOG ERROR ***', # can supply 'subject' instead of 'script'
		msg     => $str,
	); 

	$JUST_TESTING 
		? warn Dumper \%args
		: $tools->mail_admin(\%args);
}