import sys
import socket

hosts = {}
groups = {}
services = {}
checks = []

def add_host(x):
	x = x[1:]
	parts = x.split (",")
	try:
		ip = socket.gethostbyname (parts[0])
	except:
		print "Failed to lookup host " + parts[0]
		sys.exit (1)
	hosts[parts[0]] = (parts[0][0].upper() + parts[0][1:], ip)

	for y in parts[1:]:
		checks.append ((parts[0], y))

def add_service(x):
	x = x[1:]
	parts = x.split (",")
	services[parts[0]] = (parts[1], ",".join (parts[2:]))

def add_group(x):
	x = x[1:]
	parts = x.split (",")
	groups[parts[0]] = (parts[1], parts[2:])
	for x in parts[2:]:
		if (not x in hosts):
			print "For group " + parts[0] + " I don't know about host " + x
			sys.exit (1)

for x in sys.stdin.xreadlines():
	x = x[:-1]
	if (x == ""):
		continue
	if (x[0] == '#'):
		continue
	elif (x[0] == 'H'):
		add_host (x)
	elif (x[0] == 'G'):
		add_group (x)
	elif (x[0] == 'S'):
		add_service (x)
	else:
		print "Unknown line: " + x
		sys.exit (1)
print hosts
print groups
print services
print checks

# out hosts
f = open ("hosts.cfg", "w+")
f.write ("""# Hosts config file. Generated by nagios_conf
# (ask agl)
#

define host{
        name                            generic-host    ; The name of this host template - referenced in other host definitions, used for template recursion/resolution
        notifications_enabled           1       ; Host notifications are enabled
        event_handler_enabled           1       ; Host event handler is enabled
        flap_detection_enabled          1       ; Flap detection is enabled
        process_perf_data               1       ; Process performance data
        retain_status_information       1       ; Retain status information across program restarts
        retain_nonstatus_information    1       ; Retain non-status information across program restarts

        register                        0       ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
        check_command           check-host-alive
        max_check_attempts      10
        notification_interval   120
        notification_period     24x7
        notification_options    d,u,r

}

""")

for x in hosts.keys():
	f.write ("""define host {
	use		generic-host
	host_name	""" + x + """
	alias		""" + hosts[x][0] + """
	address		""" + hosts[x][1] + """
}
""")
f.close ()

f = open ("hostgroups.cfg", "w+")
f.write ("""# Host group file. Generated by nagios_conf.py
# (ask agl)
#

""")
for x in groups.keys():
	f.write ("""define hostgroup {
	hostgroup_name		""" + x + """
	alias			""" + groups[x][0] + """
	contact_groups		csg
	members			""" + ",".join (groups[x][1]) + """
}
""")
f.close ()

f = open ("services.cfg", "w+")
f.write ("""# Services file. Generated by nagios_conf.py
# (ask agl)
#

define service{
        name                            generic-service ; The 'name' of this service template, referenced in other service definitions
        active_checks_enabled           1       ; Active service checks are enabled
        passive_checks_enabled          1       ; Passive service checks are enabled/accepted
        parallelize_check               1       ; Active service checks should be parallelized (disabling this can lead to major performance problems)
        obsess_over_service             1       ; We should obsess over this service (if necessary)
        check_freshness                 0       ; Default is to NOT check service 'freshness'
        notifications_enabled           1       ; Service notifications are enabled
        event_handler_enabled           1       ; Service event handler is enabled
        flap_detection_enabled          1       ; Flap detection is enabled
        process_perf_data               1       ; Process performance data
        retain_status_information       1       ; Retain status information across program restarts
        retain_nonstatus_information    1       ; Retain non-status information across program restarts

        notification_interval           120
        notification_period             24x7
        notification_options            w,u,c,r
        retry_check_interval            1
        normal_check_interval           3
        is_volatile                     0
        check_period                    24x7
        max_check_attempts              3
        contact_groups                  csg



        register                        0       ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL SERVICE, JUST A TEMPLATE!
}
""")

for x in checks:
	f.write ("""define service {
	use			generic-service
	host_name		""" + x[0] + """
	service_description	""" + services[x[1]][0] + """
	check_command		""" + services[x[1]][1] + """
}
""")

