#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# «ubuntu-recovery» - OEM Config plugin for Ubuntu-Recovery
#
# Copyright (C) 2010-2011, Dell Inc. 2011, Canonical Inc.
#  - Mario Limonciello <Mario_Limonciello@Dell.com>
#  - Hsin-Yi Chen <hychen@canonical.com>

#
# This 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 2 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 application; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##################################################################################
import subprocess, os
import syslog

from ubiquity import misc
from ubiquity.plugin import PluginUI, InstallPlugin, Plugin
from ubunturecovery import disksmgr
import ubunturecovery.recovery_common as magic
import gi

NAME = 'ubuntu-recovery'
AFTER = 'usersetup'
BEFORE = None
WEIGHT = 12

#Gtk widgets
class PageGtk(PluginUI):
    """GTK frontend for the dell-recovery oem-config plugin"""
    plugin_title = 'ubiquity/text/recovery_heading_label'

    def __init__(self, controller, *args, **kwargs):
        self.controller = controller
        dvd, usb = magic.find_burners()
        oem = 'UBIQUITY_OEM_USER_CONFIG' in os.environ
        bypass_create_media_page = os.path.exists("/cdrom/.oem/bypass_create_media")
        if oem and (dvd or usb) and not bypass_create_media_page:
            try:
                gi.require_version('Gtk', '3.0')
                from gi.repository import Gtk
                builder = Gtk.Builder()
                builder.add_from_file('/usr/share/ubiquity/gtk/stepRecoveryMedia.ui')
                builder.connect_signals(self)
                self.controller.add_builder(builder)
                self.plugin_widgets = builder.get_object('stepRecoveryMedia')
                self.usb_media = builder.get_object('save_to_usb')
                self.dvd_media = builder.get_object('save_to_dvd')
                self.none_media = builder.get_object('save_to_none')
                if not dvd:
                    builder.get_object('dvd_box').hide()
                if not usb:
                    builder.get_object('usb_box').hide()
            except Exception as err:
                syslog.syslog('Could not create Ubuntu Recovery page: %s' % err)
                self.plugin_widgets = None
        else:
            self.plugin_widgets = None 

        PluginUI.__init__(self, controller, *args, **kwargs)

    def plugin_get_current_page(self):
        """Called when ubiquity tries to realize this page."""
        return self.plugin_widgets

    def get_grub_line(self):
        return self.grub_line.get_text()

    def get_type(self):
        """Returns the type of recovery to do from GUI"""
        if self.usb_media.get_active():
            return "usb"
        elif self.dvd_media.get_active():
            return "dvd"
        else:
            return "none"

    def set_type(self, value):
        """Sets the type of recovery to do in GUI"""
        if value == "usb":
            self.usb_media.set_active(True)
        elif value == "dvd":
            self.dvd_media.set_active(True)
        else:
            self.none_media.set_active(True)

class Page(Plugin):
    """Debconf driven page for the ubuntu-recovery oem-config plugin"""
    def prepare(self, unfiltered=False):
        """Prepares the debconf plugin"""
        destination = self.db.get('ubuntu-recovery/destination')
        self.ui.set_type(destination)
        
        return Plugin.prepare(self, unfiltered=unfiltered)

    def ok_handler(self):
        """Handler ran when OK is pressed"""
        destination = self.ui.get_type()
        self.preseed('ubuntu-recovery/destination', destination)
        Plugin.ok_handler(self)

class Install(InstallPlugin):
    """The ubuntu-recovery media creator install time ubiquity plugin"""
    def __init__(self, frontend, db=None, ui=None):
        self.disksmgr = disksmgr.Udisks()
        InstallPlugin.__init__(self, frontend, db, ui)

    def install(self, target, progress, *args, **kwargs):
        """Perform actual install time activities for oem-config"""
        if not 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
            return

        lang = progress.get('debian-installer/locale')
        env = os.environ
        if not lang:
            env['LANG'] = 'en_US.UTF-8'
        else:
            env['LANG'] = lang

        #can also expect that this was mounted at /cdrom during OOBE
        subprocess.call(['mount', '-o', 'remount,rw', '/cdrom'])
        subprocess.call(['grub-editenv', '/cdrom/boot/grub/grubenv',
                          'set', 'lang={}'.format(lang)])

        env['LC_ALL'] = lang
        env['LANGUAGE'] = lang.split('.')[0]

        add_grub_menu = misc.create_bool(progress.get('ubuntu-recovery/add_grub_menu'))

        if add_grub_menu:
            rec_hotkey_label = progress.get('ubuntu-recovery/recovery_hotkey/partition_label')
            rec_part = self.disksmgr.find_factory_rp_stats(rec_hotkey_label)
            if rec_part and os.path.exists('/cdrom/.disk/info'):
                rec_text = progress.get('ubuntu-recovery/grub_menu_title')
                if rec_text is None or rec_text is '':
                    # Fallback to translated string from python gtk+ builder. (LP: #1032776)
                    command = subprocess.Popen(['/usr/share/ubuntu/scripts/grub_menu_title.py'], stdout=subprocess.PIPE, stderr=None, env=env)
                    rec_text = command.communicate()[0].decode('utf-8').split('\n')[0]
                magic.process_conf_file(original = '/usr/share/ubuntu/grub/99_ubuntu_recovery',
                                        new = '/etc/grub.d/99_ubuntu_recovery',
                                        uuid = str(rec_part["uuid"]),
                                        rp_number = str(rec_part["number"]),
                                        recovery_text = rec_text)
                os.chmod('/etc/grub.d/99_ubuntu_recovery', 0o755)
                subprocess.call(['update-grub'],env=env)
                
        rec_type = progress.get('ubuntu-recovery/destination')
        if rec_type != "none":
            subprocess.call(['/usr/share/ubuntu/bin/generate-recovery-iso','--oobe'])
            with open("/usr/share/ubuntu/oobe_recovery_type","w") as f:
                f.write("%s\n" % rec_type)

        return InstallPlugin.install(self, target, progress, *args, **kwargs)
