#!/usr/bin/env python

import re
import getopt
import sys

def usage():
	print("Script to handle more complex text processing portions of NagVis installation")
	print("Normally you will not call this script directly.")
	print("Copyright 2011-2018 Nagios Enterprises, LLC")
	print("")
	print("Usage:  ./adjust_config.py --mode <mode>")
	print("")
	print("Options:")
	print(" -h, --help")
	print("    Print detailed help screen")
	print(" -m, --mode")
	print("    Set to run in either core or xi mode (default xi)")
	print("")
	sys.exit(0)

def main(argv):
	try:
		opts, args = getopt.getopt(argv, "hm:", ["help", "mode="])
	except getopt.GetoptError:
		usage()
		sys.exit(127)
	if len(opts) == 0:
		mode = "xi"
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			usage()
		elif opt in ("-m", "--mode"):
			if arg in ("core", "Core", "CORE"):
				mode = "core"
			elif arg in ("xi", "XI", "ix", "IX"):
				mode = "xi"
			else:
				print("Invalid mode.  Please use either core or xi.")
				sys.exit(127)
		else:
			usage()

	config = open('/usr/local/nagvis/etc/nagvis.ini.php', 'r')
	configlines = config.readlines()
	config.close()

	whitespace = re.compile('^\s*$') # Matches a blank line
	globre = re.compile('^;?\[global\]\S*') # Matches global settings section
	lmre = re.compile('^;?logonmodule\S*') # Matches logon module type setting
	lvre = re.compile('^;?logonenvvar\S*') # Matches logon environment variable setting
	defre = re.compile('^;?\[defaults\]\S*') # Matches default settings section
	pathre = re.compile('^;?\[paths\]\S*') # Matches paths settings section
	bere = re.compile('^;?backend\S*') # Matches default backend setting
	hure = re.compile('^;?hosturl\S*') # Matches hosturl setting
	hgure = re.compile('^;?hostgroupurl\S*') # Matches hostgroupurl setting
	sure = re.compile('^;?serviceurl\S*') # Matches serviceurl setting
	sgure = re.compile('^;?servicegroupurl\S*') # Matches servicegroupurl setting
	host_downtime_url = re.compile('^;?host_downtime_url\S*')
	host_ack_url = re.compile('^;?host_ack_url\S*')
	service_downtime_url = re.compile('^;?service_downtime_url\S*')
	service_ack_url = re.compile('^;?service_ack_url\S*')
	cgire = re.compile('^;?htmlcgi\S*') # Matches global htmlcgi setting
	bendo1re = re.compile('^;?\[backend_ndomy_1\]\S*') # Matches first ndomy backend
	betypere = re.compile('^;?backendtype\S*') # Matches backend type
	dbure = re.compile('^;?dbuser\S*') # Matches database user name
	dbpre = re.compile('^;?dbpass\S*') # Matches database password
	dbinre = re.compile('^;?dbinstancename\S*') # Matches database instance name

	# Find section for [global]

	for line in configlines:
		if globre.match(line) != None:
			globalstart = configlines.index(line)
			break

	for line in configlines[globalstart:]:
		if whitespace.match(line) != None:
			globalend = configlines[globalstart:].index(line) + globalstart
			break

	# Edit [global] section

	for line in configlines[globalstart:globalend]:
		if lmre.match(line) != None:
			if mode == "xi":
				configlines[ globalstart + configlines[globalstart:globalend].index(line) ] = 'logonmodule="LogonSession"\n'
			else:
				configlines[ globalstart + configlines[globalstart:globalend].index(line) ] = 'logonmodule="LogonEnv"\n'
		elif lvre.match(line) != None:
			if mode == "core":
				configlines[ globalstart + configlines[globalstart:globalend].index(line) ] = 'logonenvvar="REMOTE_USER"\n'

	# Find section for [defaults]

	for line in configlines:
		if defre.match(line) != None:
			defaultstart = configlines.index(line)
			break

	for line in configlines[defaultstart:]:
		if whitespace.match(line) != None:
			defaultend = configlines[defaultstart:].index(line) + defaultstart
			break

	# Edit [defaults] section

	for line in configlines[defaultstart:defaultend]:
		if bere.match(line) != None:
			configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'backend="nagiosxi"\n'
		elif hure.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'hosturl="[htmlcgi]/status.php?host=[host_name]"\n'
			else:
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'hosturl="[htmlcgi]/status.cgi?host=[host_name]"\n'
		elif hgure.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'hostgroupurl="[htmlcgi]/status.php?show=services&hostgroup=[hostgroup_name]"\n'
			else:
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'hostgroupurl="[htmlcgi]/status.cgi?hostgroup=[hostgroup_name]"\n'
		elif sure.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'serviceurl="[htmlcgi]/status.php?show=servicedetail&host=[host_name]&service=[service_description]&dest=auto"\n'
			else:
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'serviceurl="[htmlcgi]/extinfo.cgi?type=2&host=[host_name]&service=[service_description]"\n'
		elif sgure.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'servicegroupurl="[htmlcgi]/status.php?show=services&servicegroup=[servicegroup_name]"\n'
			else:
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'servicegroupurl="[htmlcgi]/status.cgi?servicegroup=[servicegroup_name]"\n'
		elif host_downtime_url.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'host_downtime_url="[html_cgi]/../nagioscore/ui/cmd.php?cmd_typ=55&host=[name]"\n'
		elif host_ack_url.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'host_ack_url="[html_cgi]/../nagioscore/ui/cmd.php?cmd_typ=96&host=[name]&force_check"\n'
		elif service_downtime_url.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'service_downtime_url="[html_cgi]/../nagioscore/ui/cmd.php?cmd_typ=56&host=[name]&service=[service_description]"\n'
		elif service_ack_url.match(line) != None:
			if mode == "xi":
				configlines[ defaultstart + configlines[defaultstart:defaultend].index(line) ] = 'service_ack_url="[html_cgi]/../nagioscore/ui/cmd.php?cmd_typ=7&host=[name]&service=[service_description]&force_check"\n'

	# Find section for [paths]

	for line in configlines:
		if pathre.match(line) != None:
			pathstart = configlines.index(line)
			break

	for line in configlines[pathstart:]:
		if whitespace.match(line) != None:
			pathend = configlines[pathstart:].index(line) + pathstart
			break

	# Edit [paths] section

	for line in configlines[pathstart:pathend]:
		if cgire.match(line) != None:
			if mode == "xi":
				configlines[ pathstart + configlines[pathstart:pathend].index(line) ] = 'htmlcgi="/nagiosxi/includes/components/xicore"\n'
			else:
				configlines[ pathstart + configlines[pathstart:pathend].index(line) ] = 'htmlcgi="/nagios/cgi-bin"\n'

	# Find section for [backend_nagiosxi]

	for line in configlines:
		if bendo1re.match(line) != None:
			backendstart = configlines.index(line)
			break

	for line in configlines[backendstart:]:
		if whitespace.match(line) != None:
			backendend = configlines[backendstart:].index(line) + backendstart
			break
			
	# Edit [backend_ndomy_1] section

	for line in configlines[backendstart:backendend]:
		if betypere.match(line) != None:
			configlines[ backendstart + configlines[backendstart:backendend].index(line) ] = 'backendtype="ndomy"\n'
		elif dbure.match(line) != None:
			configlines[ backendstart + configlines[backendstart:backendend].index(line) ] = 'dbuser="ndoutils"\n'
		elif dbpre.match(line) != None:
			configlines[ backendstart + configlines[backendstart:backendend].index(line) ] = 'dbpass="n@gweb"\n'
		elif dbinre.match(line) != None:
			configlines[ backendstart + configlines[backendstart:backendend].index(line) ] = 'dbinstancename="localhost"\n'

	# Write out changes
	config = open('/usr/local/nagvis/etc/nagvis.ini.php', 'w')
	config.writelines(configlines)
	config.close()
	
	print("Updated Nagvis config.")
	
	# Update the template "default.context.html"
	template = open('/usr/local/nagvis/share/userfiles/templates/default.context.html', 'r')
	templatelines = template.readlines()
	template.close()

	# Replace [html_cgi] with /nagios/cgi-bin
	new = []
	for line in templatelines:
		new.append(line.replace('[html_cgi]', '/nagios/cgi-bin'));
	
	# Write changes to the template	
	template = open('/usr/local/nagvis/share/userfiles/templates/default.context.html', 'w')
	template.writelines(new)
	template.close()
	
	print("Patched template files.")
	print("Adjustment completed!")

if __name__ == "__main__":
	sys.exit(main(sys.argv[1:]))