#!/usr/bin/python

import os
import dbus
import sys

from gettext import gettext as _, bindtextdomain, textdomain

from gi.repository import GObject, Gtk

from aptdaemon.client import AptClient
from defer import inline_callbacks
from aptdaemon import policykit1
from aptdaemon.gtk3widgets import AptProgressDialog
from aptdaemon.errors import NotAuthorizedError


script = "/usr/bin/landscape-client-settings-ui"


def on_transaction_done(transaction, exit):
    Gtk.main_quit()
    # Install may have failed
    if os.path.exists(script):
        os.execl(sys.executable, sys.executable, script)


@inline_callbacks
def install_package():
    aptclient = AptClient()
    bus = dbus.SystemBus()
    name = bus.get_unique_name()
    action = policykit1.PK_ACTION_INSTALL_OR_REMOVE_PACKAGES
    flags = policykit1.CHECK_AUTH_ALLOW_USER_INTERACTION
    try:
        yield policykit1.check_authorization_by_name(name, action, flags=flags)
    except NotAuthorizedError:
        Gtk.main_quit()
    transaction = yield aptclient.install_packages(["landscape-client-ui"])
    transaction.connect("finished", on_transaction_done)
    dialog = AptProgressDialog(transaction)
    dialog.run(close_on_finished=True, show_error=True)


def main():
    bindtextdomain("landscape-client", "/usr/share/locale")
    textdomain("landscape-client")

    dialog = Gtk.MessageDialog(
        flags=Gtk.DialogFlags.MODAL, type=Gtk.MessageType.INFO,
        buttons=Gtk.ButtonsType.CANCEL)
    link = "<a href=\"https://landscape.canonical.com\">%s</a>" % _("Find out more...")
    dialog.set_markup(
        "<big><b>%s</b></big>\n\n%s\n\n%s\n\n%s" % (
            _("Landscape client"),
            _("Landscape is an easy-to-use commercial systems management and "
              "monitoring service offered by Canonical that helps "
              "administrators manage multiple machines efficiently."), link,
            _("You need to install Landscape client to be able to configure it. "
              "Do you want to install it now?")))
    dialog.set_title(_("Install Landscape client?"))
    button = dialog.add_button(_("Install"), Gtk.ResponseType.YES)
    button.grab_focus()
    result = dialog.run()
    dialog.destroy()
    if result == Gtk.ResponseType.YES:
        install_package()
    else:
        Gtk.main_quit()
    return False


if __name__ == "__main__":
    if not os.path.exists(script):
        GObject.idle_add(main)
        Gtk.main()
    else:
        os.execl(sys.executable, sys.executable, script)
