#!/usr/bin/env perl
use strict;
use warnings;
use DBI;
use Getopt::Long;
use Pod::Usage;

my $conn_host = 'localhost';
my $conn_port = 5432;
my $conn_user = 'musicbrainz';
my $conn_database = 'musicbrainz';
my $conn_schema = 'musicbrainz';
my $help = 0;

GetOptions(
    "host|h:s"     => \$conn_host,
    "port|p:i"     => \$conn_port,
    "user|U:s"     => \$conn_user,
    "database|d:s" => \$conn_database,
    "schema|s:s"   => \$conn_schema,
    "help|?"       => \$help
) or pod2usage(3);
pod2usage(3) if $help;

my $dsn = sprintf("dbi:Pg:dbname=%s;host=%s;port=%d",
                  $conn_database, $conn_host, $conn_port);
my $dbh = DBI->connect($dsn, $conn_user)
    or critical("Failed to connect with '$dsn' as user '$conn_user': " . DBI->errstr);

my $res = $dbh->selectrow_array(
    "SELECT
       CASE
         WHEN ago > '2 days'::interval THEN
           concat_ws(':', 'CRITICAL', 2,
             'Statistics have not been collected for over 2 days')
         WHEN ago > '28 hours'::interval THEN
           concat_ws(':', 'WARNING', 1,
             'Statistics have not been collected for over 28 hours')
         WHEN ago IS NULL THEN
           concat_ws(':', 'CRITICAL', 2,
             'No statistics could be found')
         ELSE
           concat_ws(':', 'OK', 0)
       END
     FROM (
       SELECT
         (SELECT now() - date_collected
          FROM statistic
          ORDER BY date_collected DESC LIMIT 1) AS ago
     ) a")
    or critical('Failed to collect statistics: ' . $dbh->errstr);

my ($status, $exit, $summary) = split(':', $res);

print $status, "\n";
print $summary, "\n" if $summary;
exit $exit;

sub critical {
    my $message = shift;
    print "CRITICAL\n$message\n";
    exit 2;
}

__END__

=head1 NAME

statistics-collected - Nagios check for statistics collections

=head1 SYNOPSIS

statistics-collected

 Options:
   --host=<host>      Database host. Defaults to localhost
   -h <host>

   --port=<port>      Database port. Defaluts to 5432
   -p <port>

   --user=<user>      PostgreSQL database user. Defaults to musicbrainz
   -u <user>

   --schema=<schema>  MusicBrainz schema containing 'statistics' table.
   -s <schema>        Defaults to musicbrainz.

   --database=<db>    MusicBrainz database name. Defaults to musicbrainz
   -d <db>

=head1 DESCRIPTION

Nagios check to make sure statistics have been collected

Checks that statistics have been collected recently. The alerts are:

=over 4

=item CRITICAL

Satistics have not been collected at all.

The command fails to connect to the database.

Statistics have not been collected in over 2 days.

=item WARNING

Statistics have not been collected in over 28 hours.

=item OK

Otherwise

=cut
