<?php

header("Content-type: application/json");

error_reporting(E_ERROR | E_WARNING | E_PARSE);
define("JSON_PRETTY_PRINT",1);
$fqdn = 0;
$max_service = array("is_flapping", "current_state");
$collect_service = array("plugin_output", "performance_data");
$collect_service = array(); # Skip collect services for now.

print "// Process script: $_SERVER[SCRIPT_NAME]\n";

$statusfile = "status.dat"; #/usr/local/nagios/var/status.dat"; /usr/local/nagios/var/status.dat /var/lib/icinga/status.dat

print "// \$statusfile: ".realpath($statusfile)."\n";

$sf = fopen($statusfile, "r");
$section = "";
$host_name = "";
$cntsec = array();
$n["general"]["statusfile"] = $statusfile;
$n["general"]["delay"] = 1;
while (!feof($sf)) {
	$line = fgets($sf);
	if (preg_match("/^([a-z_]+)\s*[{]\s*$/", $line, $m)) {
		#print "$m[1]\n";
		$section = $m[1];
		@$cntsec[$section]++;
	}
	# info programstatus hoststatus servicestatus contactstatus hostcomment servicecomment
	if (in_array($section, array("hoststatus","servicestatus"))) {
		if (preg_match("/^\t([a-z_]+)=(.*)$/", $line, $m)) {
			$key = $m[1];
			$val = is_numeric($m[2]) ? intval($m[2]) : $m[2];
			if ("host_name" == $key) {
				if ($fqdn) {
					$host_name = $val;
				} else {
					$a = explode(".",$val);
					$host_name = $a[0];
				}
			} elseif ("service_description" == $key) {
				$service_description = $val;
			} elseif (in_array($key, $max_service)) {
				if (!isset($n["node"][$host_name][$key])) {
					$n["node"][$host_name][$key] = $val;
				}
				if ($val > $n["node"][$host_name][$key]) {
					$n["node"][$host_name][$key] = $val;
				}
			} elseif (in_array($key,$collect_service)) {
				if (strlen($val)) {
					$n["node"][$host_name]["service"][$key] = $val;
				}
			}
		}
	}
}

if (JSON_PRETTY_PRINT) {
	print preg_replace("/[}],\"/","},\n\"", json_encode($n) );
} else {
	print json_encode($n);
}

?>
