#!/usr/bin/perl


# Auto importer. Created by Russell Jennings. Copyright 2010 Include information Management, released under GPLv2 license. 
# Questions?  russellj@include-im.com 

# Version 1. it's crude and there is certainly room for improvement. But, it works. (well, enough.) Run via cron, on demand, or on trigger. 

### set variables here...

$indexhistoryfile='/tmp/autoimportlog.txt';  # path to where to keep the index history
$verbose=1;	# determines if print statements work or not. 
$cfgdirectory='/usr/local/nagios/etc/objects/autoimported'; # directory where config files should be output to. no trailing /
$objectcache='/usr/local/nagios/var/objects.cache'; # where's the object cache, dr.watson?
# make sure there aren't any other "settings" you need to change in the script. 

### Sub routines

sub servicegroup_check($$$$$)  {
        my($alias, $objectcache, $servicegroup, $site, $cfgdirectory) = @_;
        unless (`/bin/cat $objectcache | /bin/grep \"$servicegroup\"`) {
                $groupfile="$cfgdirectory/$site" . "_groups.cfg";
                print "the servicegroup is $servicegroup\n\n";
                unless (`/bin/cat $groupfile | /bin/grep \"$servicegroup\"`) {
		open GROUPFILE, "+>>", $groupfile or die $!;
      ### the next "line" is the actual output to file
                                                print GROUPFILE ("
define servicegroup{
        servicegroup_name       $servicegroup
        alias                   $alias
        }
         ");
              close GROUPFILE;
		}
        }
}


chomp (@list= `/bin/cat /usr/local/nagios/var/nagios.log | /bin/grep "not be found\!"`);
### remove unix timestamp
foreach (@list) {
	$_=~ s/\[.*\]//g;
	}
if ($list[0] eq "") {
        if ($verbose == 1) { print "array is empty. exiting...\n"; }
        exit 0;
	}

### remove duplicates (host or service entries) because one's enough.
@newlist = "";
foreach (@list) {
        if( $_ ~~ @newlist ) {  ### this checks if current list item exists in other array
                }
	else {
		push(@newlist,$_);
		}
	
        # check each item for a match on the list, remove from array list if found
        $listarrayindex++;
        }

@list=@newlist;
if ($verbose == 1) { print "here's what i found in the list:\n"; foreach (@list) { print "$_\n";} }
if (!@list) {
	if ($verbose == 1) { print "array is empty. exiting...\n"; }
	exit 0;
} 
if (-e $indexhistoryfile)
{ 
	$indexfound=1;
	if ($verbose == 1) { print "I found an index history\n"; }
}
else
{
	if ($verbose == 1) { print "I did not find an index history\n"; }
	$indexfound=0;
}

####  remove any that have already been added by reading the history file

if ($indexfound == 1) {
	$listarrayindex =0;
open FILE, $indexhistoryfile or die "Can not open file for input!\n";
	chomp( @indexhistory = <FILE>);
close FILE;
if ($verbose == 1) { print "\nthe index history contains\n"; foreach(@indexhistory) { print "$_\n";} }
if ($verbose == 1) { print "removing items already added...\n";}	
foreach (@list) {
	if( $_ ~~ @indexhistory )  ### this checks if current list item exists in other array
		{
		if ($verbose == 1) { print "removing from array:$_\n"; }
		delete $list[$listarrayindex]
		}
	# check each item for a match on the list, remove from array list if found
	$listarrayindex++;
	}
}

if ($verbose == 1) { print "\nthe list now contains\n"; foreach(@list) { print "$_\n";} }

### at this point our array only contains valid entires. Either it got washed or it doesn't need to be! 

### below we use two for each statements. we generate any host entries first, then generate the services. 

###
# HOSTS
###

foreach (@list) { # look for hosts only
$hostgroup=""; # reset every time...
	if ($_  =~ m/but the host/g) {  # we found us a host! 
		if ($_ =~ m/host \'(.*?)\'/) {	
			$cfgfilename="$cfgdirectory/$1.cfg";
			$thehost=$1;
			if ($thehost =~ m/^(.*?)_/) {   ### if you find a site tag... AKA site1_, site2_,
                       		$site=$1;
				$hostgroup=$site . "_group";  # site1_group
			if ($hostgroup ne "") {
                                $hostline="hostgroups\t\t$hostgroup";
        	                unless (`/bin/cat $objectcache | /bin/grep \"$hostgroup\"`) {
	         		       	$groupfile="$cfgdirectory/$site" . "_groups.cfg"; 
		                	unless (`/bin/cat $groupfile | /bin/grep \"$hostgroup\"`) {
                open GROUPFILE, "+>>", $groupfile or die $!;
      ### the next "line" is the actual output to file. I can't say I'm proud of what I did, only that it had to be done. 
                                                print GROUPFILE ("
define hostgroup{
        hostgroup_name       $hostgroup
        alias                $hostgroup
        }               
         ");
              close GROUPFILE;
                }
        }
     }
                         else    {
                                 $hostline="";
                                 }

		}

			if (-e $cfgfilename) {		# if the host file exists, skip it. 
				if ($verbose == 1) { print "the file $cfgfilename already exists. skipping.\n"; }
				}
			else { # otherwise, open it and write...
				open CFGFILE, "+>>", $cfgfilename or die $!;
		### the next "line" is the actual output to file
				print CFGFILE ("
define host {
                host_name                       $thehost
                alias                           $thehost
                use                             passive-host
		$hostline
		}
");	
				close CFGFILE;
				} # end else
			} # end host extracting if
		} # end if we found a host	 
	} # end for each

# begin blatant duplication! (now we do the same thing for services. not that any would get put in for the hosts we just created anyway, but it just makes sense anyway)


###
# Services
###

# 
# Services can have automatic service groups created, based on the name. Should be pretty self explanatory. 
#
foreach (@list) { # look for services only
$servicegroup="";     ### reset
        if ($_  =~ m/but the service/g) {  # we found us a service!     
                if ($_ =~ m/service '(.*?)' on host \'(.*?)\'/) {  
                        $cfgfilename="$cfgdirectory/$2.cfg";
                        $thehost=$2;
			$theservice=$1;
			if ($thehost =~ m/^(.*?)_/) {   ### if you find a site tag...
				$site=$1;
				if ($theservice =~ m/^CPU/i) {    ### generate site-servicegroup
					$servicegroup=$site . "_CPU";  # site1_CPU
					$alias=$site . " Loads";
					&servicegroup_check($alias, $objectcache, $servicegroup, $site, $cfgdirectory);
					}
			if ($theservice =~ m/Drive|partition|share/i) {    ### generate site-servicegroup
                                $servicegroup=$site . "_DISK";
				$alias=$site . " Storage";
                                &servicegroup_check($alias, $objectcache, $servicegroup, $site, $cfgdirectory);
                                }
			if ($theservice =~ m/dwa|domino|zimbra|ex-change|25/i) {    ### generate site-servicegroup
                                $servicegroup=$site . "_MAIL";
				$alias=$site . " Mail";
                                &servicegroup_check($alias, $objectcache, $servicegroup, $site, $cfgdirectory);
                                }
			if ($theservice =~ m/memory/i) {    ### generate site-servicegroup
                                $servicegroup=$site . "_MEM";
				$alias=$site . " Memory";
                                &servicegroup_check($alias, $objectcache, $servicegroup, $site, $cfgdirectory);
                                }
			} # end the 'if we found a site' tag... and move on to greener pastures. Preferably pasteurized pastures. Mmm… milkshakes..
                        	if (-e $cfgfilename) {         # here, we make SURE the file exists. otherwise, your gonna have a bad time
					unless (`/bin/cat $cfgfilename | /bin/grep \"$theservice\"`) {
						open CFGFILE, "+>>", $cfgfilename or die $!;  
						### the next "line" is the actual output to file It's not elegant but sometimes ay just gotta get'r done. 
						if ($servicegroup ne "") {				
							$serviceline="servicegroups\t\t\t$servicegroup";        
						}                        
						else    {
							$serviceline="";
							}
		
print CFGFILE ("
define service{
        service_description             $theservice 
        host_name                       $thehost
        use                             passive-service
	$serviceline
	 }
");
                                		close CFGFILE;
                                	} # end config write
			
				} # end unless
                        
			else {
				if ($verbose == 1) { print "i couldn't find the file $cfgfilename.\n"; }
                             } # end else
                        } # end host/service extracting if
                } # end if we found a host/service
        } # end for each

### append our list to the index history file
 open FILE, "+>>", $indexhistoryfile or die $!;
while( @list) {
    $tmp = shift( @list);
	if ($tmp ne "") 
	{
   		print FILE ( $tmp . "\n" );  # adding a CR/LF character to maintain file format
	}
}
close FILE;

# Reload, not restart. If there's (somehow) a config error, a restart could be dangerous,especially if crooned!
`/etc/init.d/nagios reload`;