#!/moira/bin/perl -Tw

# $Id: nagios-cluster.gen,v 1.2 2009-06-17 14:45:33 jweiss Exp $
# The following exit codes are defined and MUST BE CONSISTENT with the
# error codes the library uses:
$MR_DBMS_ERR = 47836421;
$MR_OCONFIG = 47836460;

$outfile = '/moira/dcm/nagios-cluster.out';

use DBI;

umask 022;
open(OUT, ">$outfile") || exit $MR_OCONFIG;
print OUT "# This File is automatically generated by Moira.  Do not edit.\n\n";


$dbh = DBI->connect("dbi:Oracle:moira", "moira", "moira")
  || exit $MR_DBMS_ERR;


$sth1 = $dbh->prepare("SELECT m.name FROM machine m, clusters c, mcmap p " .
		     "WHERE m.status=1 AND c.name='cluster' AND " .
		     "(m.mach_id=p.mach_id AND p.clu_id=c.clu_id)")
    || exit $MR_DBMS_ERR;
$sth1->execute || exit $MR_DBMS_ERR;

my %clusters;
while (($name) = $sth1->fetchrow_array) {
    next if $name eq "[NONE]";
    $name = lc($name);
    my $cluster = $name;
    $cluster =~ s/\..*$//;
    $cluster =~ s/\-[^\-]*$//;
#    print "$name\t$cluster\n";
    push @$cluster, $name;
    $clusters{$cluster}++;


    print OUT <<"END";
define host{
	host_name		$name
	alias			$name
	address			$name
	contact_groups		noone
	use			generic-host
	}

define service{
	host_name		$name
	contact_groups		noone
	use			ping-service
	}

define service{
	host_name		$name
	contact_groups		noone
	use			no-ssh-service
	}

define service{
	host_name		$name
	contact_groups		noone
	use			no-telnet-service
	}

define service{
	host_name		$name
	contact_groups		noone
	use			no-ftp-service
	}

define service{
	host_name		$name
	contact_groups		noone
	use			public-service
	}

END
}

foreach $key (sort (keys %clusters)) {
    print OUT <<END;
define hostgroup {
	hostgroup_name          $key
	alias                   $key
END
    print OUT "\tmembers\t\t";
    $maybecomma = "";
    foreach $machine (@$key) {
	print OUT "$maybecomma$machine";
	$maybecomma = ",";
    }
    print OUT "\n\t}\n\n";
}


print OUT "\n### Printers\n\n";

$sth0 = $dbh->prepare("SELECT UNIQUE m.name FROM machine m, printers p " .
		     "WHERE (p.type = 'DORM' OR p.type ='CLUSTER') " .
		     "AND p.mach_id = m.mach_id AND m.status=1")
    || exit $MR_DBMS_ERR;

$sth0->execute || exit $MR_DBMS_ERR;

while (($name) = $sth0->fetchrow_array) {
    next if $name eq "[NONE]";
    $name = lc($name);
    push(@allprinters, $name);
    print OUT <<"END";
define host{
	host_name		$name
	alias			$name
	address			$name
	contact_groups		noone
	use			generic-host
	}

define service{
	host_name		$name
	contact_groups		noone
	use			ping-service
	}

define service{
	host_name		$name
	contact_groups		noone
	use			hpjd-service
	}

END

}

print OUT <<END;
define hostgroup{
	hostgroup_name          printers
	alias                   printers
END

print OUT "\tmembers\t\t";

$maybecomma = "";
foreach $printer (@allprinters) {
    print OUT "$maybecomma$printer";
    $maybecomma = ",";
}

print OUT "\n\t}\n\n";

close(OUT);
$dbh->disconnect;

exit 0;
