#!/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 Getopt::Std;
getopts('t'); # days, testing, query output
our($opt_t); # warn $opt_t; exit;

use strict;
use warnings;

my $JUST_TESTING = $opt_t || 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::Printer;
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 $subject = 'CRON LOG ERROR';
my $today   = DateTime->today;

my @errors;
# 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
		push @errors, $_; # retains new-line marker
		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;
}

if ( @errors ) {
    $subject .= 'S' if @errors > 1;

	my %args = (
		subject => '***' . $subject . '***',
		msg     => join '', reverse @errors, # revert to cronological order
	);

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