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

# Copyright (C) 2020 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 subprocess

from ubiquity import plugin

NAME = 'nv-postact'
AFTER = 'network'
WEIGHT = 20

def postActions():
    (status, output) = subprocess.getstatusoutput("systemctl restart keyboard-setup")

    if status != 0:
        print("Failed to restart keyboard-setup service")

    # only apply netplan for DCS
    platfuncs = "/usr/local/sbin/nv_scripts/plat_funcs.bash"
    cmd = ". " + platfuncs + " && plat_needs_oem_config_postact_netplan_apply"
    (status, output) = subprocess.getstatusoutput(cmd)
    if status == 0:
        (status, output) = subprocess.getstatusoutput("netplan apply")
        if status != 0:
            print("Failed to run netplan apply")

    # Restore ubuntu-tasks
    task_file = "/usr/share/tasksel/descs/ubuntu-tasks.desc"
    task_file_moved = task_file + ".orig"
    if os.path.exists(task_file_moved):
        os.rename(task_file_moved, task_file)

    return

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

class Page(plugin.Plugin):
    def prepare(self, unfiltered=False):
        return ['/bin/true']

class Install(plugin.InstallPlugin):
    def install(self, target, progress, *args, **kwargs):
        postActions()
        return plugin.InstallPlugin.install(self, target, progress, *args, **kwargs)
