# Copyright (c) TuxCare, Inc. All rights reserved.
# Licensed under TUXCARE LICENSE AGREEMENT
# https://tuxcare.com/legal/

import os
import re
import sys

from . import config, constants, kcare, log_utils, process_utils
from .errors import KcareError

if False:  # pragma: no cover
    from typing import Any, Dict, List, Optional, Set, Tuple, Union  # noqa: F401

FREEZER_BLACKLIST = '/etc/sysconfig/kcare/freezer.modules.blacklist'
CONFLICTING_MODULES_RE = re.compile('(kpatch.*|ksplice.*|kpatch_livepatch.*)')


def get_freezer_blacklist():
    # type: () -> Set[str]
    result = set()
    if os.path.isfile(FREEZER_BLACKLIST):
        f = open(FREEZER_BLACKLIST, 'r')
        for line in f:
            result.add(line.rstrip())
        f.close()
    return result


def detect_conflicting_modules(modules):
    # type: (List[str]) -> None
    for module in modules:
        if CONFLICTING_MODULES_RE.match(module):
            raise KcareError(
                "Detected '{0}' kernel module loaded. Please unload that module first".format(module),
                status='conflicting kernel module',
            )


def _insmod_failure_reason(stderr):
    # type: (Optional[str]) -> str
    """Return the kernel's reason for an insmod failure, from the last line insmod prints.

    For example, 'Key was rejected by service'.  The line differs by insmod:
    - kmod: "insmod: ERROR: could not insert module <path>: <reason>"
    - module-init-tools: "insmod: error inserting '<path>': -1 <reason>"
    """
    lines = [line.strip() for line in (stderr or '').splitlines() if line.strip()]
    if not lines:
        return ''
    reason = re.sub(r'^-?\d+\s+', '', lines[-1].rsplit(': ', 1)[-1])
    return reason[: constants.UPDATE_ERROR_DETAIL_MAX_LENGTH]


def load_kmod(kmod, **kwargs):
    # type: (str, **Any) -> None
    cmd = ['/sbin/insmod', kmod]
    for key, value in kwargs.items():
        cmd.append('{0}={1}'.format(key, value))
    code, _, stderr = process_utils.run_command(cmd, catch_stdout=True, catch_stderr=True)
    if code != 0:
        reason = _insmod_failure_reason(stderr)
        raise KcareError(
            'Unable to load kmod ({0} {1}{2}). Try to run with `--check-compatibility` flag.'.format(
                kmod, code, ': ' + reason if reason else ''
            ),
            status='kmod load error',
            detail=reason,
        )


def check_patch_type_compatibility(ptype):
    # type: (str) -> None
    # TODO KPT-4474 patch type autodetection
    cmd = process_utils.find_cmd('modinfo')
    has_kmodlve = process_utils.run_command([cmd, 'kmodlve'], catch_stdout=True, catch_stderr=True)[0] == 0

    if has_kmodlve and ptype in ('free', 'extra'):
        # KPT-4269 kcarectl: free/extra patches confict with kmodlve
        log_utils.logerror('{0} patch type conflicts with kmodlve kernel module'.format(ptype))
        sys.exit(1)


def get_kmod_available_params(kmod):
    # type: (str) -> List[str]
    stdout = process_utils.check_output(["/sbin/modinfo", "-F", "parm", kmod])
    available_params = []
    for line in stdout.split('\n'):
        if line.strip():
            param_name, _, _ = line.partition(':')
            available_params.append(param_name)
    return available_params


def make_kmod_new_params():
    # type: () -> Dict[str, Any]
    return {
        'kpatch_debug': 1 if config.KPATCH_DEBUG else 0,
        'kmsg_output': 1 if config.KMSG_OUTPUT else 0,
        'kcore_output': config.KCORE_OUTPUT_SIZE if config.KCORE_OUTPUT else 0,
        'kdumps_dir': config.KDUMPS_DIR if isinstance(config.KDUMPS_DIR, str) else "",
        'enable_crashreporter': 1 if config.ENABLE_CRASHREPORTER else 0,
    }


def update_all_kmod_params():
    # type: () -> None
    if config.KDUMPS_DIR and not os.path.exists(config.KDUMPS_DIR):
        os.makedirs(config.KDUMPS_DIR)

    for param, val in make_kmod_new_params().items():
        update_kmod_param(param, val)


def update_kmod_param(kmod_param_name, param_value):
    # type: (str, Any) -> None
    params_root = '/sys/module/kcare/parameters'
    param_path = os.path.join(params_root, kmod_param_name)

    if not os.path.exists(param_path):
        return

    try:
        with open(param_path, 'w') as f:
            f.write(str(param_value))
    except Exception:  # pragma: no cover
        log_utils.kcarelog.error('failed to set %s kmod param to %s', kmod_param_name, param_value)


def load_kcare_kmod(khash, level):
    # type: (str, Union[str, int]) -> None
    # loaded by path from the cache: a copy under /lib/modules would need depmod, which rewrites the
    # whole module index, and a reset during that can leave the index empty and the host unbootable
    kcare_file = kcare.get_cache_path(khash, level, constants.KMOD_BIN)

    if config.KDUMPS_DIR and not os.path.exists(config.KDUMPS_DIR):
        os.makedirs(config.KDUMPS_DIR)

    kmod_params = make_kmod_new_params()
    available_kmod_params = get_kmod_available_params(kcare_file)
    kmod_params = dict((k, v) for k, v in kmod_params.items() if k in available_kmod_params)

    load_kmod(kcare_file, **kmod_params)


def unload_kmod(modname):
    # type: (str) -> None
    code, _, _ = process_utils.run_command(['/sbin/rmmod', modname], catch_stdout=True)
    if code != 0:
        raise KcareError('Unable to unload {0} kmod {1}'.format(modname, code), status='kmod unload error')


def apply_fixups(khash, current_level, modules):
    # type: (str, Union[str, int], List[str]) -> List[str]
    loaded = []
    for mod in ['vmlinux'] + modules:
        modpath = kcare.get_cache_path(khash, current_level, 'fixup_{0}.ko'.format(mod))
        if os.path.exists(modpath):
            load_kmod(modpath)
            loaded.append('fixup_{0}'.format(mod))
    return loaded


def remove_fixups(fixups):
    # type: (List[str]) -> None
    for mod in fixups:
        try:
            unload_kmod(mod)
        except Exception:
            log_utils.kcarelog.exception('Exception while unloading module %s.' % mod)


def get_freezer_style(freezer, modules):
    # type: (Optional[str], List[str]) -> Tuple[str, Optional[str], str, bool]
    if freezer:
        method = freezer
    elif config.PATCH_METHOD:
        method = config.PATCH_METHOD
    elif get_freezer_blacklist().intersection(modules):
        # blacklist module found, use smart freezer
        # xxx: this branch could be safely removed when smart would work by default
        return 'freeze_conflict', freezer, config.PATCH_METHOD, True
    else:
        # user doesn't provide patch method and no conflicting modules loaded
        return 'default', freezer, config.PATCH_METHOD, False

    # non default patch method, translate it into form accepted by kpatch_ctl
    patch_method_map = {
        'NONE': 'freeze_none',
        'NOFREEZE': 'freeze_none',
        'FULL': 'freeze_all',
        'FREEZE': 'freeze_all',
        'SMART': 'freeze_conflict',
    }

    method = method.upper()

    if method in patch_method_map:
        method = patch_method_map[method]
    else:
        raise KcareError(
            'Unable to detect freezer style ({0}, {1}, {2}, {3})'.format(method, freezer, config.PATCH_METHOD, False),
            status='freezer style detection error',
        )
    return method, freezer, config.PATCH_METHOD, False
