#!/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 warnings
# this is a deprecation warning we see on rhel6, but the
# functionality doesn't seem to exist in public api yet
# Note that you do not see this on python2.7 systems as
# deprecationWarnings are ignored by default
warnings.filterwarnings(action="ignore",
                        category=DeprecationWarning,
                        message="^The dbus_bindings module is not public API and will go away soon.")

import sys
import os
import dbus
import dbus.service
import dbus.glib
import dbus.exceptions
import dbus.dbus_bindings
import gtk
import logging
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.
    from subscription_manager.i18n import configure_i18n
    configure_i18n(with_glade=True)

    from subscription_manager.gui import managergui
    from subscription_manager import logutil
    from subscription_manager.i18n_optparse import OptionParser, \
        WrappedIndentedHelpFormatter, USAGE
except ImportError, e:
    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__':
    parser = OptionParser(usage=USAGE,
                          formatter=WrappedIndentedHelpFormatter())
    parser.add_option("--register", action='store_true',
                      help=_("launches the registration dialog on startup"))
    options, args = parser.parse_args(args=sys.argv)

    logutil.init_logger()
    log = logging.getLogger('subscription-manager-gui')
    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")
        # Attempt to raise the running instance to the forefront
        remote_object = bus.get_object(BUS_NAME, BUS_PATH)
        remote_object.show_window(dbus_interface=BUS_NAME)
    else:
        try:
            main = managergui.MainWindow(auto_launch_registration=options.register)

            # 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:
            log.exception(e)
            systemExit(1, e)
