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

import sys
import os
import glib
import time

# Allow running from local path
path = os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), ".."))
if os.path.exists(path):
    sys.path.insert(0, path)

# Logging
import gnome15.g15logging as g15logging
logger = g15logging.get_root_logger()

#
import gobject
import gnome15.util.g15pythonlang as g15pythonlang
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(session_dbus):
    try :
        session_bus.get_object('org.gnome15.Gnome15', '/org/gnome15/Service').GetServerInformation()
        return True
    except Exception as e:
        logger.debug("Did not found enabled service", exc_info = e)
        return False

def start_service(options): 

    if g15pythonlang.module_exists("setproctitle"):
        import setproctitle
        setproctitle.setproctitle(os.path.basename(os.path.abspath(sys.argv[0])))
    else:
        # Not a big issue
        logger.debug("No setproctitle, process will be named 'python'")

    # Start the loop    
    try :
        import gnome15.g15service as g15service
        service = g15service.G15Service(None, no_trap=options.no_trap)
        service.exit_on_no_devices = options.exit_on_no_devices
        g15service.logger.setLevel(logger.level) 
        service.start_loop()
    except dbus.exceptions.NameExistsException as e:
        logger.debug("DBus service already exist", exc_info = e)
        print "Gnome15 desktop service is already running"
        sys.exit(1)
    
if __name__ == "__main__":
    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("-f", "--foreground", action="store_true", dest="foreground",
        default=False, help="Run desktop service in foreground.")
    parser.add_option("-n", "--notrap", action="store_true", dest="no_trap",
        default=False, help="Do not try to trap signals.")
    parser.add_option("-x", "--exit", action="store_true", dest="exit_on_no_devices",
        default=False, help="Exit immediately if there are no devices.")
    (options, args) = parser.parse_args()
    
    if options.log_level != None:      
        logger.setLevel(g15logging.get_level(options.log_level))
        
    session_bus = None
        
    if len(args) == 1 and ( args[0] == "stop" or args[0] == "restart" ):
        session_bus = dbus.SessionBus()
        if not check_service_status(session_bus):
            if args[0] == "stop":
                print "Gnome15 desktop service is not running"
        else:            
            session_bus.get_object('org.gnome15.Gnome15', '/org/gnome15/Service').Stop()
            while check_service_status(session_bus):
                pass
        session_bus.close()
            
    if len(args) == 0 or ( len(args) == 1 and ( args[0] == "start" or args[0] == "restart" ) ):
        session_bus = dbus.SessionBus()
        if check_service_status(session_bus):
            print "Gnome15 desktop service already running"
        else:
            if options.foreground or ( not options.foreground and os.fork() == 0 ):
                start_service(options)
