#!/usr/bin/env php
<?php

/**
 * Nagios compatible script to export data from the monitor page.
 *
 * Outputs a single line like: `WARNING: (ok: 12, info: system_update, warning: sys_log)`
 *
 * Usage:
 *
 * In an NRPE compatibe config file:
 * `command[check_ispconfig]=/usr/bin/sudo /usr/local/ispconfig/server/check_ispconfig.php`
 *
 * /etc/sudoers.d/ispconfig:
 * ```
 * Cmnd_Alias  CHECK_ISPCONFIG = /usr/local/ispconfig/server/check_ispconfig.php
 *
 * nagios  ALL = NOPASSWD : CHECK_ISPCONFIG
 * ```
 */


define('SCRIPT_PATH', dirname($_SERVER["SCRIPT_FILENAME"]));
require SCRIPT_PATH."/lib/config.inc.php";
require SCRIPT_PATH."/lib/app.inc.php";

ini_set('error_reporting', E_ALL & ~E_NOTICE);

$server_state = 'ok';
$retval = 0;
$server_states = array();
$state_list = array();

$records = $app->dbmaster->queryAllRecords("SELECT DISTINCT type, state FROM monitor_data
		WHERE server_id = ? AND state != 'no_state'", $conf['server_id']);

foreach($records as $record) {
	$server_states[$record['state']][] = $record['type'];
}

foreach ($server_states as $state => $data) {
	if ($state == 'ok') {
		$state_list[] = "$state: " . count($data);
	}
	else {
		$state_list[] = "$state: " . join(', ', $data);
	}
}
if (empty($server_states)) {
	$server_state = 'unknown';
	$retval = 3;
}
elseif (is_array($server_states['critical']) && count($server_states['critical']) > 0 || is_array($server_states['error']) && count($server_states['error']) > 0) {
	$server_state = 'critical';
	$retval = 2;
}
elseif ($server_states['warning'] > 0) {
	$server_state = 'warning';
	$retval = 1;
}

$status_line = strtoupper($server_state) . ': (' . join(', ', $state_list) . ')';

echo $status_line . PHP_EOL;
exit($retval);
