#! /usr/bin/perl
# by Hans Schou 2011
# Usage:
#   cat hostnames | ./svgautomap.pl > <SVG-file>
# Example:
#   grep host_name= /var/lib/nagios/status.dat | cut -d= -f2 | sort -u | ./svgautomap.pl > index.svg

$nagios_detail = "/nagios/cgi-bin/extinfo.cgi?type=1&amp;host=";

$debug = 0;
if ($debug) { 
	printf("\e[2J");
} else {
	print << "EOF";
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg viewBox="0 0 1600 800"
     xmlns="http://www.w3.org/2000/svg" version="1.1"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     >
  <title>Nagios/Icinga SVG demo</title>
  <desc>Example of how data from nagios/icinga can be displayed in SVG</desc>
  <script xlink:href="load-status-nagios-json.js"/>
  <script type="application/ecmascript"><![CDATA[
    function changeColor(evt) {
      var rectangle = evt.target;
      var currentRadius = rectangle.getAttribute("fill");
      if (currentRadius == "red")
        rectangle.setAttribute("fill", "green");
      else
        rectangle.setAttribute("fill", "red");
    }
  ]]></script>
  <defs>
     <rect id="N" width="25" height="25" fill="grey" onclick="changeColor(evt)"/>
  </defs>
EOF
}

$x = 0;
$y = 0;
$hx = $x;	# High x and y
$hy = $y;

$base_x = 4;
$base_y = 2;

while (<>) {
	chomp;
	$host_name = $_;
	if ($debug) {
		printf("\e[%d;%dH%s", $y*2+$base_y, $x*3+$base_x, $host_name);
	} else {
		printf("\t<a xlink:href=\"$nagios_detail%s\"><use xlink:href=\"#N\" x=\"%d\" y=\"%d\" id=\"%s\" title=\"%s\"/></a>\n", $host_name, $x*100+10, $y*60+80, $host_name, $host_name);
	}
	if ($hx == $hy and $x == $hx and $y == $hy) {
		# Start new right most column
		$hx = ++$x;
		$y = 0;
	} else {
		if ($x < $hx) {
			# next step horizontal bottom
			++$x;
		} else {
			# verital right most, next step down
			if (++$y > $hy) {
				# swith to new line, bottom
				$hy = $y;
				$x = 0;
			}
		}
	}
}

if ($debug) {
	printf "\n\n\n\n";
} else {
	print << "EOF";
  <text onclick="loadStatus()" x="10" y="35" font-family="Verdana" font-size="24" text-anchor="left">
	Click at me - if color does not change
  </text>
</svg>
EOF
}
