#!/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

# Import modules
# if not found in execution directory search modules in Python site modules
try:
    import nagstamonConfig, nagstamonGUI, nagstamonActions
except:
    from Nagstamon import nagstamonConfig, nagstamonGUI, nagstamonActions

# initiate configuration
conf = nagstamonConfig.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
    print err
    Resources = ""

    
###### 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)

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