#!/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 dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)

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("-p", "--profile", action="store_true", dest="profile",
        default="", help="Name of profile to activate. Defaults to automatic selection.")
    parser.add_option("-s", "--screens", action="store_true", dest="screens",
        default="", help="Which device(s) to use. Defaults to best device. \
Names are in the format [model]_[index]. So if you have two G13 keyboards \
and a G19, to select the first G13 you would use g13_0.")
    (options, args) = parser.parse_args()
    if len(args) == 0:
        print "You must provide the command to launch through Gnome15 as an argument."
        sys.exit(2)
    
    if options.log_level != None:      
        logger.setLevel(g15logging.get_level(options.log_level))
        
    session_bus = dbus.SessionBus()
    try :
        service = session_bus.get_object('org.gnome15.Gnome15', \
                               '/org/gnome15/Service')
    except Exception as e:
        logger.debug("D-Bus service not available.", exc_info = e)
        print "Gnome15 desktop service is not running. Applications may not be \
launched through it. You can start the service using g15-desktop-service."
        sys.exit(1)
        
    service.Launch(options.profile, options.screens, args)
    