#!/usr/local/bin/python
version = "0.0.3"
#####################################################################
# Fluxspace - main program
#
# Converted during build from "main.py" to the executable "main".
# The local python path is inserted in order to make it self-running
# and have the proper process name.
#####################################################################

import os
import sys
import getopt
import string
import fluxspace
import fluxspace.config
from fluxspace.process import Processes

def Abort(retcode = 0, message = None):
    if message is not None and message != '':
        print 'fluxspace: %s' % message
    else:
        print 'Unknown exception caught'
    if retcode != 0:
        print '<abort>'
    sys.exit(retcode)

def Usage(retcode = 0, message = None):
    if message is not None and message != '':
        print message
    print '''
Usage: fluxspace [OPTIONS] [ACTION]

       OPTIONS
          -c,--config CONFIG    specify config file name (default=%s)
          -d,--display DISPLAY  specify X display (override DISPLAY variable)
          -h,--help             display this help message
          -v,--verbose          display verbose trace messages
          -V,--version          display version number

        ACTION
          start    starts fluxpace, if not already running
          restart  restarts running fluxspace or starts new one (default)
          stop     stops fluxspace and child processes
''' % (fluxspace.config.defaultConfigFileName)
    Abort(retcode)

actions = ('start', 'restart', 'stop')

######################################################################
class Controller(fluxspace.Controller):
######################################################################
    def __init__(self, display, verbose):
        fluxspace.Controller.__init__(self, display, verbose)
    def BadElement(self, severity, message, element):
        lineInfo = ''
        if element.line > 0:
            lineInfo = 'line %d - ' % element.line
        fmt = 'Configuration error - %sElement "%s": %s'
        self.Message(severity, fmt % (lineInfo, element.name, message))

######################################################################
if __name__ == '__main__':
######################################################################

    verbose = 0

    try:
        display = os.environ["DISPLAY"]
        opts, args = getopt.getopt(sys.argv[1:], 'c:d:hvV', ['config=', 'display=', 'help', 'verbose', 'version'])
    except getopt.error, message:
        Usage(1, message)
    except KeyError, e:
        Abort(2, 'Environment variable "%s" not set' % e)
    except:
        Usage(3)

    for opt in opts:
        if opt[0] == '-c' or opt[0] == '--config':
            configFileName = opt[1]
        elif opt[0] == '-d' or opt[0] == '--display':
            display = opt[1]
        elif opt[0] == '-h' or opt[0] == '--help':
            Usage()
        elif opt[0] == '-v' or opt[0] == '--verbose':
            verbose = 1
        elif opt[0] == '-V' or opt[0] == '--version':
            print 'fluxspace version %s' % version
            sys.exit()

    action = 'restart'
    if len(args) > 0:
        if args[0].lower() not in actions:
            Usage(3, 'Bad action specified, "%s"' % string.join(args))
        action = args[0].lower()

    # Kill running fluxspace?
    if action in ('restart', 'stop'):
        processes = Processes()
        matching = processes.Find('fluxspace')
        if len(matching) > 0:
            processes.KillByName('fluxspace', 1)
        elif action == 'stop':
            print 'Fluxspace is not running'

    controller = Controller(display, verbose)

    # Run?
    if action not in ('start', 'restart'):
        sys.exit(0)

    fluxspace.config.SetTracer(controller)
    config = fluxspace.config.Config()
    try:
        config.Load()
    except fluxspace.config.ConfigException, e:
        Abort(1, e.message)

    # Add user-specified modules
    for moduleName in config.moduleNames:
        fullModuleName = 'fluxlet.' + moduleName
        controller.Trace('Adding module "%s"...' % fullModuleName)
        controller.RegisterFluxlet(fullModuleName, config.moduleConfigs[moduleName])

    # Event loop
    controller.Trace('Starting event loop...')
    controller.StartEvents()

    config.Close()
