#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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., 31 Milk Street #960789 Boston, MA
# 02196 USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
import re

from pyanaconda.anaconda_loggers import get_module_logger
from pyanaconda.core.constants import NETWORK_CAPABILITY_TEAM
from pyanaconda.core.regexes import NM_MAC_INITRAMFS_CONNECTION
from pyanaconda.modules.common.task import Task
from pyanaconda.modules.network.device_configuration import (
    supported_wired_device_types,
    virtual_device_types,
)
from pyanaconda.modules.network.network_interface import (
    NetworkInitializationTaskInterface,
)
from pyanaconda.modules.network.nm_client import (
    add_connection_from_ksdata,
    commit_changes_with_autoconnection_blocked,
    get_config_file_connection_of_device,
    get_device_name_from_network_data,
    get_iface_from_hwaddr,
    is_bootif_connection,
    nm_client_in_thread,
    update_connection_from_ksdata,
)
from pyanaconda.modules.network.utils import (
    guard_by_system_configuration,
    is_nbft_device,
)

log = get_module_logger(__name__)


class ApplyKickstartTask(Task):
    """Task for application of kickstart network configuration."""

    def __init__(self, network_data, supported_devices, capabilities,
                 bootif, ifname_option_values):
        """Create a new task.

        :param network_data: kickstart network data to be applied
        :type: list(NetworkData)
        :param supported_devices: list of names of supported network devices
        :type supported_devices: list(str)
        :param capabilities: list of capabilities supported by the network backend
        :type capabilities: list(int)
        :param bootif: MAC addres of device to be used for --device=bootif specification
        :type bootif: str
        :param ifname_option_values: list of ifname boot option values
        :type ifname_option_values: list(str)
        """
        super().__init__()
        self._network_data = network_data
        self._supported_devices = supported_devices
        self._capabilities = capabilities
        self._bootif = bootif
        self._ifname_option_values = ifname_option_values

    @property
    def name(self):
        return "Apply kickstart"

    def for_publication(self):
        """Return a DBus representation."""
        return NetworkInitializationTaskInterface(self)

    @guard_by_system_configuration(return_value=[])
    def run(self):
        """Run the kickstart application.

        :returns: names of devices to which kickstart was applied
        :rtype: list(str)
        """
        with nm_client_in_thread() as nm_client:
            return self._run(nm_client)

    def _run(self, nm_client):
        applied_devices = []

        if not self._network_data:
            log.debug("%s: No kickstart data.", self.name)
            return applied_devices

        if not nm_client:
            log.debug("%s: No NetworkManager available.", self.name)
            return applied_devices

        for network_data in self._network_data:
            # Wireless is not supported
            if network_data.essid:
                log.info("%s: Wireless devices configuration is not supported.", self.name)
                continue

            if network_data.teamslaves and NETWORK_CAPABILITY_TEAM not in self._capabilities:
                log.info("%s: Team devices configuration is not supported.", self.name)
                continue

            device_name = get_device_name_from_network_data(nm_client,
                                                            network_data,
                                                            self._supported_devices,
                                                            self._bootif)
            if not device_name:
                log.warning("%s: --device %s not found", self.name, network_data.device)
                continue

            if is_nbft_device(device_name):
                log.debug("Ignoring nBFT device %s", device_name)
                continue

            applied_devices.append(device_name)

            connection = self._find_initramfs_connection_of_iface(nm_client, device_name)

            if connection:
                # if the device was already configured in initramfs update the settings
                log.debug("%s: updating connection %s of device %s",
                          self.name, connection.get_uuid(), device_name)
                update_connection_from_ksdata(
                    nm_client,
                    connection,
                    network_data,
                    device_name,
                    ifname_option_values=self._ifname_option_values
                )
                if network_data.activate:
                    device = nm_client.get_device_by_iface(device_name)
                    nm_client.activate_connection_async(connection, device, None, None)
                    log.debug("%s: activating updated connection %s with device %s",
                              self.name, connection.get_uuid(), device_name)
            else:
                log.debug("%s: adding connection for %s", self.name, device_name)
                add_connection_from_ksdata(
                    nm_client,
                    network_data,
                    device_name,
                    activate=network_data.activate,
                    ifname_option_values=self._ifname_option_values
                )

        return applied_devices

    def _find_initramfs_connection_of_iface(self, nm_client, iface):
        device = nm_client.get_device_by_iface(iface)
        if device:
            cons = device.get_available_connections()
            for con in cons:
                if con.get_interface_name() == iface and con.get_id() == iface:
                    return con
        return None


class PersistInitramfsConfigTask(Task):
    """Task for persisting configuration from initramfs."""
    @property
    def name(self):
        return "Persist initramfs configuration"

    def for_publication(self):
        """Return a DBus representation."""
        return NetworkInitializationTaskInterface(self)

    def _select_persistable_active_connection(self, device, cons, allow_ports=False):
        active_connection = device.get_active_connection()
        if not active_connection:
            return None

        con = active_connection.get_connection()
        if con not in cons:
            return None

        # Filter out port connections
        iface = device.get_iface()
        if self._is_port_connection(con) and not allow_ports:
            log.debug("%s: active connection %s for %s can't be used: port connection",
                      self.name, con.get_id(), iface)
            return None

        # Check if connection is bound by interface
        if con.get_interface_name() == iface:
            log.debug("%s: using active connection %s bound by interface",
                      self.name, con.get_id())
            return con

        # Check if connection is bound by mac address
        wired_setting = con.get_setting_wired()
        if wired_setting:
            mac = wired_setting.get_mac_address()
            if mac:
                log.debug("%s: using active connection %s bound by %s",
                          self.name, con.get_id(), mac)
                return con

        log.debug("%s: active connection %s for %s can't be used: not bound",
                  self.name, con.get_id(), iface)

    def _select_interface_bound_connection(self, iface, cons, allow_ports):
        for con in cons:
            if con.get_interface_name() == iface:
                if self._is_port_connection(con) and not allow_ports:
                    log.debug("%s: interface bound %s can't be used: port connection",
                              self.name, con.get_id())
                    continue
                log.debug("%s: using %s bound by interface", self.name, con.get_id())
                return con

    def _select_mac_bound_connection(self, nm_client, iface, cons, allow_ports):
        for con in cons:
            wired_setting = con.get_setting_wired()
            if not wired_setting:
                continue
            mac = wired_setting.get_mac_address()
            if not mac:
                continue
            mac_iface = get_iface_from_hwaddr(nm_client, mac)
            if mac_iface == iface:
                if self._is_port_connection(con) and not allow_ports:
                    log.debug("%s: mac bound %s can't be used: port connection",
                              self.name, con.get_id())
                    continue
                log.debug("%s: using %s bound by %s", self.name, con.get_id(), mac)
                return con

    def _select_persistent_connection_for_device(self, nm_client, device, cons, allow_ports=False):
        """Select the connection suitable to store configuration for the device.

        The connection has to be bound by interface name or mac address.
        """
        iface = device.get_iface()
        con = self._select_persistable_active_connection(device, cons, allow_ports) or \
            self._select_interface_bound_connection(iface, cons, allow_ports) or \
            self._select_mac_bound_connection(nm_client, iface, cons, allow_ports)
        return con

    @guard_by_system_configuration(return_value=[])
    def run(self):
        """Run persisting of initramfs configuration.

        :returns: names of devices for which configuration was persisted
        :rtype: list(str)
        """
        with nm_client_in_thread() as nm_client:
            return self._run(nm_client)

    def _run(self, nm_client):
        configured_ifaces = []

        if not nm_client:
            log.debug("%s: No NetworkManager available.", self.name)
            return configured_ifaces

        for device in nm_client.get_devices():
            if device.get_device_type() not in supported_wired_device_types + virtual_device_types:
                continue

            iface = device.get_iface()

            if is_nbft_device(iface or ""):
                log.debug("Ignoring nBFT device %s", iface)
                continue

            if get_config_file_connection_of_device(nm_client, iface):
                log.debug("Ignoring device %s with existing persistent config", iface)
                continue

            available_cons = device.get_available_connections()
            log.debug("%s: %s connections found for device %s", self.name,
                      [con.get_uuid() for con in available_cons], iface)
            ifs_cons = [con for con in available_cons
                        if self._is_initramfs_connection(con, iface)]
            log.debug("%s: %s initramfs connections found for device %s", self.name,
                      [con.get_uuid() for con in ifs_cons], iface)

            if not ifs_cons:
                continue

            persisted_con = None

            device_is_port = any(self._is_port_connection(con) for con in available_cons)
            if device_is_port:
                log.debug("%s: device %s has a port connection", self.name, iface)
                # Filter out potenital connection created for BOOTIF option rhbz#2175664
                port_available_cons = [c for c in available_cons if not is_bootif_connection(c)]
                # Persist connection for port created in initramfs if it is unique
                if len(port_available_cons) == 1:
                    persisted_con = self._select_persistent_connection_for_device(
                        nm_client, device, port_available_cons, allow_ports=True)

            if not persisted_con:
                persisted_con = self._select_persistent_connection_for_device(
                    nm_client, device, ifs_cons)

            if persisted_con:
                log.debug("%s: persisting initramfs connection %s for %s",
                          self.name, persisted_con.get_uuid(), iface)
                commit_changes_with_autoconnection_blocked(persisted_con, nm_client)
                configured_ifaces.append(iface)
            else:
                log.debug("%s: not persisting initramfs connection for %s",
                          self.name, iface)

        return configured_ifaces

    def _is_initramfs_connection(self, con, iface):
        con_id = con.get_id()
        return con_id in ["Wired Connection", iface] \
            or re.match(NM_MAC_INITRAMFS_CONNECTION, con_id)

    def _is_port_connection(self, con):
        return bool(con.get_setting_connection().get_controller())
