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

"""Every patch state kcarectl reports, and what each output shows for it. For now the kernel ones.

Scripts and control panel plugins parse these values, so a code or a kpatch-state never changes for
an existing state. A message may.
"""

from . import kcare

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


class KernelPatchState(object):
    """A kernel patch state and everything kcarectl reports for it.

    code: `updateCode` of --plugin-info (line 1 of its plain output)
    patch_state: `kpatch-state` of --info --json
    check_exit: exit code of --check, 0 when an update can be applied
    message: what --info, --check and --patch-info print; may take format() arguments. It says only
        what the agent knows: the newest patch available to it can still leave a vulnerability
        unpatched, so a message never calls the kernel safe
    """

    def __init__(self, code, patch_state, check_exit, message):
        # type: (int, str, int, str) -> None
        self.code = code
        self.patch_state = patch_state
        self.check_exit = check_exit
        self.message = message

    def format_message(self, **kwargs):
        # type: (**Any) -> str
        return self.message.format(**kwargs)


# one sentence per fact, the applied level first; {applied} and {available} are describe_level() results
APPLIED = 'Patch level {applied} is applied.'
AVAILABLE = "Patch level {available} is available. Run 'kcarectl --update'."

# every applied state has a second line that says whether anything newer exists. "Available to this
# server", not "released": behind an ePortal a released patch reaches the host only once the ePortal
# makes it available
LATEST = KernelPatchState(
    code=0,
    patch_state='applied',
    check_exit=1,
    message=APPLIED + '\nNo newer patch is available to this server.',
)
# a sticky setting holds the host back on purpose; {sticky} names it and starts the line
LATEST_STICKY = KernelPatchState(
    code=0,
    patch_state='applied',
    check_exit=1,
    message=APPLIED + '\n{sticky} may hold back newer patches.',
)
# the server has newer patches that need a newer agent
LATEST_FOR_AGENT = KernelPatchState(
    code=0,
    patch_state='applied',
    check_exit=1,
    message=APPLIED + '\nNewer patches need a newer kernelcare package.',
)
UPDATE_AVAILABLE = KernelPatchState(
    code=1,
    patch_state='applied',
    check_exit=0,
    message=APPLIED + '\n' + AVAILABLE,
)
NOT_APPLIED = KernelPatchState(
    code=1,
    patch_state='unset',
    check_exit=0,
    message='No patch is applied.\n' + AVAILABLE,
)
NOT_NEEDED = KernelPatchState(
    code=3,
    patch_state='unset',
    check_exit=1,
    message="This kernel doesn't require any patches.",
)
UNKNOWN_KERNEL = KernelPatchState(
    code=2,
    patch_state='unavailable',
    check_exit=1,
    # the server answers the same for a kernel too new to have patches, for one never supported and,
    # behind an ePortal, for one its feeds do not carry: no "yet"
    message='No patches are available for kernel {release} (kernel ID {khash}).',
)
INVALID_STICKY_PATCH = KernelPatchState(
    code=2,
    patch_state='unavailable',
    check_exit=1,
    message='Invalid sticky patch tag {tag} for kernel ({distro} {release}). '
    'Please check /etc/sysconfig/kcare/kcare.conf STICKY_PATCH settings',
)

# the states where no update would replace the applied level
LATEST_STATES = (LATEST, LATEST_STICKY, LATEST_FOR_AGENT)

ALL = (LATEST, LATEST_STICKY, LATEST_FOR_AGENT, UPDATE_AVAILABLE, NOT_APPLIED, NOT_NEEDED, UNKNOWN_KERNEL, INVALID_STICKY_PATCH)


def describe_level(level, release=None):
    # type: (Any, Optional[str]) -> str
    """`24 (release K20260812_0015)`; the release name carries its day. Just `24` without a release."""
    return '{0} (release {1})'.format(level, release) if release else str(level)


def applied_release(applied, latest):
    # type: (Any, Any) -> Optional[str]
    """The release of the applied level: saved when it was applied, else the latest one if that is
    the same level. None when neither says."""
    saved = kcare.read_dumped_kernel_patch_level() or {}
    if str(saved.get('level')) == str(applied) and saved.get('khash') == kcare.get_kernel_hash():
        return saved.get('release')
    if latest is not None and str(latest) == str(applied):
        return getattr(latest, 'release', None)
    return None


def describe_sticky(setting):
    # type: (Optional[Tuple[str, str]]) -> Optional[str]
    """A sticky setting, (name, value), for a message: `UPDATE_DELAY=48h`, or None."""
    if setting is None:
        return None
    if setting == ('STICKY_PATCH', 'KEY'):
        # the patch set comes from ePortal or CLN for this server's key
        return 'The sticky patch set'
    return '{0}={1}'.format(*setting)


def latest_state(applied, release, latest, sticky):
    # type: (Any, Optional[str], Any, Optional[str]) -> Tuple[KernelPatchState, str]
    """The state and message of an applied level that no update would replace.

    release: of the applied level; latest: the level get_latest_patch_level() found;
    sticky: describe_sticky() of the setting that applies, or None
    """
    applied_desc = describe_level(applied, release)
    if latest.agent_too_old:
        return LATEST_FOR_AGENT, LATEST_FOR_AGENT.format_message(applied=applied_desc)
    if sticky:
        return LATEST_STICKY, LATEST_STICKY.format_message(applied=applied_desc, sticky=sticky)
    return LATEST, LATEST.format_message(applied=applied_desc)


class UpdateStatus(object):
    """Exit codes of --status. Computed apart from the states above: an applied level is up to date
    when it is not below the latest one, and an outdated one only after STATUS_CHANGE_GAP."""

    UP_TO_DATE = 0  # also for an unknown kernel with IGNORE_UNKNOWN_KERNEL
    NOT_APPLIED = 1
    OUTDATED = 2
    UNKNOWN_KERNEL = 3


# printed by --unload; --update prints the message of the LATEST state it is in
UNLOADED_MESSAGE = 'KernelCare patches are unloaded.'
