#!/usr/bin/perl

use DBI;
use Config::INI::Reader;

my $config = Config::INI::Reader->read_file('/etc/nagios/nagiosdigger/config.ini') or die "Unable to read the configuration file!";
$config = $config->{'_'};

# connect to database
$dbh = DBI->connect("dbi:$config->{'dbi_type'}:database=$config->{'dbi_name'}:host=$config->{'dbi_host'}", $config->{'dbi_user'}, $config->{'dbi_pass'}, { RaiseError => 0, AutoCommit => 1 }) or die "cannot connect to server" . $DBI::errstr;

# determine last event
$query = "SELECT MAX(unixts) AS last_event FROM $config->{'dbi_table'}";
$query_sth = $dbh -> prepare($query);
$query_sth -> execute();
@results = $query_sth -> fetchrow_array;
$query_sth -> finish;
$last_event = $results[0];

# prepare an insert statement
$query = "INSERT INTO $config->{'dbi_table'}(unixts, year, month, day, weekday, dayofyear, isdst, hour, min, sec, host, service, status, status_type, count, description)".
	 "                VALUES(?     , ?   , ?    , ?  , ?      , ?        , ?    , ?   , ?  , ?  , ?   , ?      , ?     , ?          , ?    , ?          )";
$query_sth = $dbh -> prepare($query) || die "Couldn't prepare query: ".$dbh -> errstr;

$skipped = 0;
$inserted = 0;
while(<>)
{
	# [1105008185] SERVICE ALERT: xs4all;PING;CRITICAL;SOFT;1;CRITICAL - Plugin timed out after 10 seconds

	if ($_ =~ "^[^ ]* SERVICE ALERT")
	{
		/^\[([0-9]+)\] SERVICE ALERT: ([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);(.*)$/;
		if ($1 > $last_event)
		{
			($sec, $min, $hour, $day, $month, $year, $weekday, $dayofyear, $isdst) = localtime($1);
			$query_sth -> execute($1, $year, $month, $day, $weekday, $dayofyear, $isdst, $hour, $min, $sec, $2, $3, $4, $5, $6, substr($7, 0, 255));	

			$inserted++;
		}
		else
		{
			$skipped++;
		}
	}
}

print "Added: $inserted\nSkipped (already in database): $skipped\n";

$query_sth -> finish;
