# Copyright (c) 2015 SUSE Linux GmbH.  All rights reserved.
#
# This file is part of kiwi.
#
# kiwi 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.
#
# kiwi 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 kiwi.  If not, see <http://www.gnu.org/licenses/>
#
import re
import os
import logging
import glob
from typing import (
    Optional, List, Dict, NamedTuple
)

# project
from kiwi.defaults import Defaults
from kiwi.system.setup import SystemSetup
from kiwi.system.identifier import SystemIdentifier
from kiwi.xml_description import XMLDescription
from kiwi.xml_state import XMLState
from kiwi.path import Path
from kiwi.system.kernel import Kernel

from kiwi.exceptions import (
    KiwiTargetDirectoryNotFound,
    KiwiConfigFileNotFound,
    KiwiDiskBootImageError
)

boot_names_type = NamedTuple(
    'boot_names_type', [
        ('kernel_name', str),
        ('initrd_name', str)
    ]
)

log = logging.getLogger('kiwi')


class BootImageBase:
    """
    **Base class for boot image(initrd) task**
    """
    def __init__(
        self, xml_state: XMLState, target_dir: str,
        root_dir: Optional[str] = None,
        signing_keys: Optional[List[str]] = None,
        target_arch: Optional[str] = None
    ) -> None:
        """
        Create a base class instance of a BootImage

        The base class instance only support the common operations
        for boot images. The actual preparation and creation of an
        initrd is specific to the used initrd creation toolchain

        :param XMLState xml_state: Instance of :class:`XMLState`
        :param str target_dir: target dir to store the initrd
        :param str root_dir: system image root directory
        :param List[str] signing_keys: list of package signing keys
        :param str target_arch: target architecture
        """
        self.xml_state = xml_state
        self.target_dir = target_dir
        self.initrd_filename = ''
        self.boot_xml_state: Optional[XMLState] = None
        self.setup: Optional[SystemSetup] = None
        self.signing_keys = signing_keys
        self.target_arch = target_arch
        self.boot_root_directory = root_dir or ''

        if not os.path.exists(target_dir):
            raise KiwiTargetDirectoryNotFound(
                'target directory %s not found' % target_dir
            )

        self.initrd_base_name = ''.join(
            [
                self.xml_state.xml_data.get_name(),
                '.' + Defaults.get_platform_name(),
                '-' + self.xml_state.get_image_version(),
                '.initrd'
            ]
        )
        self.post_init()

    def post_init(self) -> None:
        """
        Post initialization method

        Implementation in specialized boot image class
        """
        pass

    @staticmethod
    def has_initrd_support() -> bool:
        """
        Indicates if this instance supports actual creation of an initrd

        The method needs to be overwritten by the subclass
        implementing preparation and creation of an initrd
        """
        return False

    def include_file(self, filename: str, install_media: bool = False) -> None:
        """
        Include file to boot image

        For kiwi boot images this is done by adding package or
        archive definitions with the bootinclude attribute. Thus
        for kiwi boot images the method is a noop

        :param str filename: file path name

        :param bool install_media: include also for installation media initrd
        """
        pass

    def include_module(self, module: str, install_media: bool = False) -> None:
        """
        Include module to boot image

        For kiwi boot no modules configuration is required. Thus in
        such a case this method is a noop.

        :param str module: module to include
        :param bool install_media: include the module for install initrds
        """
        pass

    def omit_module(self, module: str, install_media: bool = False) -> None:
        """
        Omit module to boot image

        For kiwi boot no modules configuration is required. Thus in
        such a case this method is a noop.

        :param str module: module to omit
        :param bool install_media: omit the module for install initrds
        """
        pass

    def set_static_modules(
        self, modules: List[str], install_media: bool = False
    ) -> None:
        """
        Set static modules list for boot image

        For kiwi boot no modules configuration is required. Thus in
        such a case this method is a noop.

        :param list modules: list of modules to include
        :param bool install_media: lists the modules for install initrds
        """
        pass

    def write_system_config_file(
        self, config: Dict, config_file: Optional[str] = None
    ) -> None:
        """
        Writes relevant boot image configuration into configuration file
        that will be part of the system image.

        This is used to configure any further boot image rebuilds after
        deployment. For instance, initrds recreated on kernel update.

        For kiwi boot no specific configuration is required for initrds
        recreation, thus this method is a noop in that case.

        :param dict config: dictonary including configuration parameters
        :param str config_file: configuration file to write
        """
        pass

    def get_boot_names(self) -> boot_names_type:
        """
        Provides kernel and initrd names for the boot image

        :return:
            Contains boot_names_type tuple

            .. code:: python

                boot_names_type(
                    kernel_name='INSTALLED_KERNEL',
                    initrd_name='DRACUT_OUTPUT_NAME'
                )

        :rtype: boot_names_type
        """
        kernel = Kernel(
            self.boot_root_directory
        )
        kernel_info = kernel.get_kernel()
        if not kernel_info:
            raise KiwiDiskBootImageError(
                'No kernel in boot image tree %s found' %
                self.boot_root_directory
            )
        dracut_output_format = self._get_boot_image_output_file_format(
            kernel_info.version
        )
        return boot_names_type(
            kernel_name=kernel_info.name,
            initrd_name=dracut_output_format.format(
                kernel_version=kernel_info.version
            )
        )

    def prepare(self) -> None:
        """
        Prepare new root system to create initrd from. Implementation

        is only needed if there is no other root system available

        Implementation in specialized boot image class
        """
        raise NotImplementedError

    def create_initrd(
        self, mbrid: Optional[SystemIdentifier] = None,
        basename: Optional[str] = None, install_initrd: bool = False
    ) -> None:
        """
        Implements creation of the initrd

        :param SystemIdentifier mbrid: instance of SystemIdentif
ier
        :param str basename: base initrd file name
        :param bool install_initrd: installation media initrd

        Implementation in specialized boot image class
        """
        raise NotImplementedError

    def is_prepared(self) -> bool:
        """
        Check if initrd system is prepared.

        :return: True or False

        :rtype: bool
        """
        return bool(os.listdir(self.boot_root_directory))

    def load_boot_xml_description(self) -> None:
        """
        Load the boot image description referenced by the system image
        description boot attribute
        """
        log.info('Loading Boot XML description')
        boot_description_directory = self.get_boot_description_directory()
  