#!/usr/bin/python
# encoding: utf-8


# Garbage collection
import gc
gc.enable()
#gc.set_debug(gc.DEBUG_LEAK)

try:
    import pygtk
    pygtk.require("2.0")
except Exception, err:
    print
    print err
    print
    print "Could not load pygtk, maybe you need to install python gtk."
    print
    import sys
    sys.exit()
import gtk
import gobject

# Initiate Config
# if modules are not available from central python install try the ones in the same directory
try:
    from Nagstamon.nagstamonConfig import Config
except:
    from nagstamonConfig import Config
conf = Config()

# check for old settings when upgrading from a nagstamon version < 0.8 and convert them
conf.Convert_Conf_to_Multiple_Servers()

# try to get resources path if nagstamon got be installed by setup.py
try:
    import pkg_resources
    Resources = pkg_resources.resource_filename("Nagstamon", "resources")
except Exception, err:
    # set resources to "" in case there are no resources available from setup.py
    Resources = ""
    
# initialize GUI and actions
# if modules are not available from central python install try the ones in the same directory
try:
    from Nagstamon import nagstamonGUI
except:
    import nagstamonGUI
try:
    from Nagstamon import nagstamonActions
except:
    import nagstamonActions

    
###### MAIN ##############

# necessary gobject thread initialization
gobject.threads_init()

# dictinary for servers
servers = dict()

# create servers
for server in conf.servers.values():
    servers[server.name] = nagstamonActions.CreateServer(server, conf)

# Initiate Output
output = nagstamonGUI.GUI(conf=conf, servers=servers, Resources=Resources)

# start threaded nagios server checking loop
nagstamonActions.StartRefreshLoop(servers=servers, conf=conf, output=output)

# if unconfigured nagstamon shows the settings dialog to get settings
if conf.unconfigured == True:
    nagstamonGUI.Settings(servers=servers, output=output, conf=conf)

# if checking for new version is set check now
if str(conf.check_for_new_version) == "True":
    check = nagstamonActions.CheckForNewVersion(servers=servers, output=output, mode="startup")
    check.start()

try:
    # Gtk Main Loop
    gtk.main()
    # save config
    conf.SaveConfig()
except Exception, err:
    output.error_dialog(err)
