#! /usr/bin/env python3
# -*- coding: utf-8; indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
#
# Copyright (C) 2012 Canonical Limited
#
# 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/>.

from gi.repository import Gtk, GObject
import subprocess, logging, dbus, os

DBUS_BUS_NAME = 'com.ubuntu.RecoveryMedia'
DBUS_INTERFACE_NAME = 'com.ubuntu.RecoveryMedia'

class Handler:
    def __init__(self, window, dialog):
        self.window = window
        self.dialog = dialog 
        self.usb_device = False
        self.creating_iso = False
        window.show_all()

    def check_and_create_iso(self):
        if self.creating_iso is False and os.access("/usr/share/ubuntu/recovery.iso", os.R_OK):
            if self.usb_device:
                subprocess.call(["usb-creator-gtk", "-i", "/usr/share/ubuntu/recovery.iso"])
            else:
                subprocess.call(["brasero", "-i", "/usr/share/ubuntu/recovery.iso"])
            Gtk.main_quit()
            return False

        if self.creating_iso is False and not os.access("/usr/share/ubuntu/recovery.iso", os.R_OK):
            self.creating_iso = True
            self.dialog.show_all()

            try:
                bus = dbus.SystemBus()
                iface = dbus.Interface(bus.get_object(DBUS_BUS_NAME, '/RecoveryMedia'), DBUS_INTERFACE_NAME)
            except Exception as err:
                logging.error('install function exception while creating dbus backend: %s', str(err))

            try:
                iface.create()
            except dbus.DBusException as err:
                if hasattr(err, '_dbus_error_name') and err._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':
                    pass
                else:
                    logging.error("Received %s when closing recovery-media-backend", str(err))

        if self.creating_iso is True and os.access("/usr/share/ubuntu/recovery.iso", os.R_OK):
            self.creating_iso = False
            self.dialog.hide()

            try:
                bus = dbus.SystemBus()
                iface = dbus.Interface(bus.get_object(DBUS_BUS_NAME, '/RecoveryMedia'), DBUS_INTERFACE_NAME)
            except Exception as err:
                logging.error('install function exception while creating dbus backend: %s', str(err))

            try:
                iface.request_exit()
            except dbus.DBusException as err:
                if hasattr(err, '_dbus_error_name') and err._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':
                    pass
                else:
                    logging.error("Received %s when closing recovery-media-backend", str(err))

        return True

    def onDeleteWindow(self, *args):
        Gtk.main_quit(*args)

    def onCreateDVD(self, button):
        self.window.hide()
        self.usb_device = False
        GObject.timeout_add(2000, self.check_and_create_iso)

    def onCreateUSB(self, button):
        self.window.hide()
        self.usb_device = True
        GObject.timeout_add(2000, self.check_and_create_iso)


def main():
    builder = Gtk.Builder()
    builder.set_translation_domain('ubuntu-recovery')
    builder.add_from_file('/usr/share/ubuntu/recovery-media-creator.ui')
    window = builder.get_object("recovery_media_creator")
    dialog = builder.get_object("create_recovery_iso")
    spinner = builder.get_object("spinner")
    spinner.start()
    builder.connect_signals(Handler(window, dialog))
    Gtk.main()

if __name__ == '__main__':
    main()

# vim:fileencodings=utf-8:expandtab:tabstop=4:shiftwidth=4:softtabstop=4
