# -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-

# Copyright (C) 2016 NVIDIA Corporation
#
# 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 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 program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import pathlib
import configparser

from ubiquity import plugin

def FrontendIsUbiquity():
    return 'UBIQUITY_FRONTEND' in os.environ and os.environ['UBIQUITY_FRONTEND'] == 'debconf_ui'

NAME = 'nv-eula'
AFTER = None
WEIGHT = 200

class NVEulaGtkOnly(Exception):
    pass

class NVEulaInteractiveOnly(Exception):
    pass

class NVEulaPageBase(plugin.PluginUI):
    def __init__(self):
        plugin.PluginUI.__init__(self)
        self.skip = False

class PageGtk(NVEulaPageBase):
    def __init__(self, controller, *args, **kwargs):
        NVEulaPageBase.__init__(self)
        from gi.repository import Gtk

        if self.is_automatic:
            # Not sure how we'd get here, but it seems reasonable to raise an
            # exception.
            raise NVEulaInteractiveOnly(
                "The EULA must be accepted interactively."
            )

        self.controller = controller
        builder = Gtk.Builder()
        self.controller.add_builder(builder)
        builder.add_from_file(os.path.join(
            os.environ['UBIQUITY_GLADE'], 'stepNVEula.ui'))
        builder.connect_signals(self)
        self.controller.add_builder(builder)
        self.page = builder.get_object('stepNVEula')

        # For DGX-5825, Update EULA format and read EULA from enterprise_eula.txt to align with the nv-eula.sh
        parser = configparser.ConfigParser()
        for sw_release in ['dgx','dcs','egx']:
            sw_release_file = "/etc/" + sw_release + "-release"
            if pathlib.Path(sw_release_file).exists():
                with open(sw_release_file) as f:
                    parser.read_string("[RELEASE]\n" + f.read())
                    my_swbuild_version = parser.get('RELEASE', sw_release.upper() + '_SWBUILD_VERSION',fallback="VERSION_NOT_FOUND").strip('\'"')
                    break

        eula_txt = "[" + my_swbuild_version + "]\n\n" + pathlib.Path('/usr/share/nvidia/enterprise_eula.txt').read_text()
        builder.get_object('textbuffer1').set_text(eula_txt)

        self.plugin_widgets = self.page

class PageKde(NVEulaPageBase):
    def __init__(self, controller, *args, **kwargs):
        raise NVEulaGtkOnly("KDE interface not implemented, sorry.")

class PageDebconf(plugin.PluginUI):
    plugin_title = 'ubiquity/text/breadcrumb_prepare'

class Page(plugin.Plugin):
    def prepare(self, unfiltered=False):
        if FrontendIsUbiquity():
            # Call nv-eula.sh to handle the debconf case
            return ['/usr/share/nvidia/nv-eula.sh']

        # End here, don't return a command to fall through to
        # Page[Gtk|Kde] cases
