#!/usr/bin/env python2
 
#  Gnome15 - Suite of tools for the Logitech G series keyboards and headsets
#  Copyright (C) 2011 Brett Smith <tanktarta@blueyonder.co.uk>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Wrapper to launch games (and other applications), monitor their output for 
patterns and send events to interested DBUS clients 
"""


import sys
import os
import glib

# Logging
import logging
logging.basicConfig(format='%(threadName)s:%(name)s:%(message)s')
logger = logging.getLogger()

LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL}

import gobject
gobject.threads_init()

# DBUS - Use to check current desktop service status or stop it
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from dbus.mainloop.glib import threads_init
threads_init()
DBusGMainLoop(set_as_default=True)

# Server host class

def check_service_status(system_dbus):
    try :
        system_bus.get_object('org.gnome15.GameWrap', '/org/gnome15/GameWrap').GetServerInformation()
        return True
    except Exception as e:
        logger.debug("D-Bus service not available.", exc_info = e)
        return False

def start_service(args, bus, no_trap=False,):    
    try :
        import setproctitle
        setproctitle.setproctitle(os.path.basename(os.path.abspath(sys.argv[0])))
    except ImportError as ie:
        # Not a big issue
        logger.debug("No setproctitle, process will be named 'python'", exc_info = ie)

    # Start the loop    
    try :
        import gw   
        service = gw.G15GameWrapperServiceController(args, bus, no_trap=no_trap)
        service.start_loop()
    except dbus.exceptions.NameExistsException as nee:
        logger.debug("D-Bus service already running", exc_info = nee)
        print "GameWrap service is already running"
        sys.exit(1)
    
if __name__ == "__main__":
    """
    Allow arguments to be passed to gamewrap itself. If the first command line
    argument begins with - or --, then gamewrap options follow until the first
    argument that doesn't start with - or --
    """
    import optparse
    parser = optparse.OptionParser()
    parser.add_option("-l", "--log", dest="log_level", metavar="INFO,DEBUG,WARNING,ERROR,CRITICAL",
        default="warning" , help="Log level")
    parser.add_option("-n", "--notrap", action="store_true", dest="no_trap",
        default=False, help="Do not try to trap signals.")
    (options, args) = parser.parse_args()
    
    level = logging.NOTSET
    if options.log_level != None:      
        level = LEVELS.get(options.log_level.lower(), logging.NOTSET)
        logger.setLevel(level = level)
        
    the_bus = dbus.SessionBus()
    if check_service_status(the_bus):
        print "GameWrap service already running"
    else:
        start_service(args, the_bus, options.no_trap)
