#
# Copyright 2017-2021 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""PatchRunner integration hook for Lookup Service

This module integrates Lookupsvc patching scripts with the
PatchRunner Framework.

"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017-2021 VMware, Inc. All rights reserved.'

import logging
import os
import sys

from extensions import extend, Hook
from l10n import msgMetadata as _T, localizedString as _
from patch_specs import ValidationResult, Question, Mismatch, Requirements, \
    PatchInfo, RequirementsResult
from reporting import getProgressReporter
from . import utils
from cis.defaults import *
import vcsa_utils
from fss_utils import getTargetFSS  # pylint: disable=E0401

sys.path.append(os.path.join(os.path.dirname(__file__), "patches"))
patches = [
    # In order to update from version 0 to version 1, execute patch_01.py
    ("1","patch_01"),
    # adding patch_02.py to register LS grpc endpoint to envoy
    ("2","patch_02"),
]


NDU_LIMITED_DOWNTIME_FSS = "NDU_Limited_Downtime"

COMPONENT_NAME = "lookupsvc"

logger = logging.getLogger(__name__)


@extend(Hook.Discovery)
def discover(ctx):
    logger.info("Executing Discovery Hook for Lookup Service")

    return vcsa_utils.getComponentDiscoveryResult(COMPONENT_NAME,
                                                  displayName=_(
                                                   _T("lookupsvc.displayName",
                                                   "Lookup Service")))


@extend(Hook.Prepatch)
def prePatch(ctx): #pylint: disable=W0613
    '''void prePatch(PatchContext sharedCtx) throw UserUpgradeError'''


@extend(Hook.Patch)
def execute_patch(ctx):
    #This hook is invoked after the rpms are installed.

    if not vcsa_utils.isDisruptiveUpgrade(ctx) and getTargetFSS(NDU_LIMITED_DOWNTIME_FSS):
        return

    logger.info("Executing Patch Hook for Lookup Service")
    progressReporter = getProgressReporter()
    progressReporter.updateProgress(0, _(_T("lookupsvc.patch.begin",
                                            "Start Lookup Service patching")))
    _do_incremental_patching(ctx)

    progressReporter.updateProgress(100, _(_T("lookupsvc.patch.complete",
                                              "Patching Lookup service completed")))


def _do_incremental_patching(ctx):
    #Enumerate each patch and apply it as needed.
    for ver, modulePath in patches:
        logger.info("Checking if need patch %s on version %s"
                     % (ver, modulePath))
        mod = __import__(modulePath)

        if utils.is_patch_needed(ver):
            logger.info("Patch %s needed" % (modulePath))
            mod.doPatching(ctx)
            logger.info('Patch %s applied' % (modulePath))

            utils.update_patch_version(ver)
