#!/usr/bin/perl

=head1 CapMan

CapMan is a tool to query many servers using SNMP and store the received data
in RRD files. Those files can be used to create graphs of the collected data.
CapMan does not need a database of any sort. It uses it's configuration and is
very modular, i.e. flexible.

=head1 See Also

L<CapMan::Config>, L<CapMan::Dispatcher>, L<CapMan::Services>, L<CapMan::Tools>.

=cut

BEGIN
{
	if ($0 =~ m#(.+)/#)
	{
		chdir ($1) or die ("chdir: $!");
	}
}

use strict;
use warnings;
use lib qw(lib);
use vars qw($DEBUG);

use POSIX qw(:sys_wait_h);

use CapMan::Config qw(read_config get_all_customers get_all_hosts);
use CapMan::Dispatcher qw(query_host);
use CapMan::Services qw(load_plugins);

our $Processes = 10;

sub sigchld_handler
{
	while (waitpid (-1, WNOHANG) > 0)
	{
		$Processes++;
	}
	$SIG{'CHLD'} = \&sigchld_handler;
}
$SIG{'CHLD'} = \&sigchld_handler;

$DEBUG = 0;

if (grep { $_ eq '-d' or $_ eq '--debug' } (@ARGV))
{
	$DEBUG = 1;
}
elsif (defined ($ENV{'DEBUG'}) and $ENV{'DEBUG'})
{
	$DEBUG = 1;
}

read_config ();
load_plugins ();

for (get_all_customers ())
{
	my $customer = $_;
	print "Collecting all hosts for customer $customer.\n" if ($::DEBUG);

	for (get_all_hosts ($customer))
	{
		my $host = $_;

		sleep (1) while ($Processes < 1);

		if (!$DEBUG)
		{
			my $pid = fork ();

			if (!defined ($pid))
			{
				die ("Unable to fork: $!");
			}
			elsif ($pid == 0)
			{
				query_host ($customer, $host);
				exit (0);
			}
			else
			{
				$Processes--;
			}
		}
		else
		{
			print STDOUT "DEBUG: Processing host $host\n";
			query_host ($customer, $host);
		}
	}
}

while (waitpid (-1, 0) != -1 and !$DEBUG)
{
	# there are more children
}

exit (0);

=head1 Author

Florian octo Forster E<lt>octo@noris.netE<gt> fuer die noris network AG
L<http://noris.net/>

=cut
