#!/usr/bin/python
#
# wrapper for subscription Manager commandline tool.
#
# Copyright (c) 2010 Red Hat, Inc.
#
# Authors: Pradeep Kilambi
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#


if __name__ != '__main__':
    raise ImportError("module cannot be imported")

import sys
import os
import dbus
import dbus.service, dbus.glib, dbus.exceptions
import dbus.dbus_bindings
import gtk
import gettext
_ = gettext.gettext

# these def's moved 
try:
    from dbus.bus import REQUEST_NAME_REPLY_PRIMARY_OWNER
    from dbus.bus import REQUEST_NAME_REPLY_ALREADY_OWNER
except ImportError:
    from dbus.dbus_bindings import REQUEST_NAME_REPLY_PRIMARY_OWNER
    from dbus.dbus_bindings import REQUEST_NAME_REPLY_ALREADY_OWNER

gtk.gdk.threads_init()

def systemExit(code, msgs=None):
    "Exit with a code and optional message(s). Saved a few lines of code."

    if msgs:
        if type(msgs) not in [type([]), type(())]:
            msgs = (msgs, )
        for msg in msgs:
            sys.stderr.write(str(msg)+'\n')
    sys.exit(code)

BUS_NAME = "com.redhat.SubscriptionManagerGUI"
BUS_PATH = "/gui"

_LIBPATH = "/usr/share/rhsm"
# add to the path if need be
if _LIBPATH not in sys.path:
    sys.path.append(_LIBPATH)


# quick check to see if you are a super-user.
if os.getuid() != 0:
    sys.stderr.write('ERROR: must be root to execute\n')
    sys.exit(8)

try:
    # this has to be done first thing (due to module level translated vars,
    # like in constants.py
    from subscription_manager.managerlib import configure_i18n
    configure_i18n(with_glade=True)

    from subscription_manager.gui import managergui, messageWindow
    from subscription_manager import logutil
except ImportError, e:
    raise
    systemExit(2, "Unable to find Subscription Manager module.\n"
                  "Error: %s" % e)
                  
class SubscriptionManagerService(dbus.service.Object):

    def __init__(self, window):
        self.window = window
        bus_name = dbus.service.BusName(BUS_NAME, bus = dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, BUS_PATH)
        
    @dbus.service.method(dbus_interface=BUS_NAME)
    def show_window(self):
        self.window.present()

if __name__ == '__main__':
    logutil.init_logger()
    try:
        bus = dbus.SessionBus()
    except dbus.exceptions.DBusException:
        # Just ignore it if for some reason we can't find the session bus
        bus = None

    bus_name = dbus.service.BusName(BUS_NAME, bus = dbus.SessionBus())
    request_name_res = dbus.dbus_bindings.bus_request_name(bus.get_connection(), bus_name.get_name())

    if bus and ((request_name_res != REQUEST_NAME_REPLY_PRIMARY_OWNER) and \
	(request_name_res != REQUEST_NAME_REPLY_ALREADY_OWNER)):
        print _("subscription-manager-gui is already running")
        messageWindow.InfoDialog(_('Subscription Manager is already running'))
        
        show = bus.get_object(BUS_NAME, BUS_PATH).get_dbus_method('show_window')
        show()
    else:
        try:
            main = managergui.MainWindow()
            
            # Hook into dbus service - only if it is available
            if bus:
                SubscriptionManagerService(main.main_window)

            # Exit the gtk loop when the window is closed
            main.main_window.connect('hide', gtk.main_quit)

            sys.exit(gtk.main() or 0)
        except SystemExit, e:
            #this is a non-exceptional exception thrown by Python 2.4, just
            #re-raise, bypassing handle_exception
            raise e
        except KeyboardInterrupt:
            systemExit(0, "\nUser interrupted process.")
        except Exception, e:
            systemExit(1, e)

