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

import os
import platform

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

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

    FreezerStyle = Tuple[str, Optional[str], str, bool]
    PatchLevel = Union[str, int]


class ApplyPatchError(KcareError):
    status = 'patch apply error'

    def __init__(self, code, freezer_style, level, patch_file, *args, **kwargs):
        # type: (int, FreezerStyle, PatchLevel, str, Any, Any) -> None
        super(ApplyPatchError, self).__init__(*args, **kwargs)
        self.code = code
        self.freezer_style = freezer_style
        self.level = level
        self.patch_file = patch_file
        self.distro = platform_utils.get_distro()[0]
        self.release = platform.release()

    def __str__(self):
        # type: () -> str
        return 'Unable to apply patch ({0} {1} {2} {3} {4}, {5})'.format(
            self.patch_file,
            self.level,
            self.code,
            self.distro,
            self.release,
            ', '.join([str(i) for i in self.freezer_style]),
        )


def kpatch_ctl_tuning_args():
    # type: () -> List[str]
    args = []  # type: List[str]
    if config.KPATCH_RETRIES is not None:
        args.extend(['-r', str(config.KPATCH_RETRIES)])
    if config.KPATCH_TIMEOUT_SEC is not None:
        args.extend(['-t', str(config.KPATCH_TIMEOUT_SEC)])
    return args


def kpatch_ctl_patch(patch_file, khash, level, description, freezer_style):
    # type: (str, str, PatchLevel, str, FreezerStyle) -> None
    args = [constants.KPATCH_CTL]
    blacklist_file = kcare.get_cache_path(khash, level, config.BLACKLIST_FILE)
    if os.path.exists(blacklist_file):
        args.extend(['-b', blacklist_file])
    args.extend(['patch', '-d', description])
    args.extend(['-m', freezer_style[0]])
    args.extend(kpatch_ctl_tuning_args())
    args.append(patch_file)
    code, _, _ = process_utils.run_command(args, catch_stdout=True)
    if code != 0:
        raise ApplyPatchError(code, freezer_style, level, patch_file)


def kpatch_ctl_unpatch(freezer_style):
    # type: (FreezerStyle) -> None
    # TODO KPT-4001 refactoring, extract kpatch_ctl run to a class with patch/unpatch/etc methods with logging and error handling
    code, stdout, stderr = process_utils.run_command(
        [constants.KPATCH_CTL, 'unpatch', '-m', freezer_style[0]] + kpatch_ctl_tuning_args(),
        catch_stdout=True,
        catch_stderr=True,
    )
    if code != 0:
        log_utils.logerror('Error unpatching, kpatch_ctl stdout:\n{0}\nstderr:\n{1}'.format(stdout, stderr), print_msg=False)
        raise KcareError('Error unpatching [{0}] {1}'.format(code, str(freezer_style)), status='unpatch error')
