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

This module integrates TrustManagement 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 fss_utils import getTargetFSS
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
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"),
    ("2","patch_02"),
    ("3","patch_03"),
    ("4","patch_04"),
    ("5","patch_05"),
    ("6","patch_06"),
]

NDU_LIMITED_DOWNTIME_FSS = "NDU_Limited_Downtime"

COMPONENT_NAME = "trustmanagement"

logger = logging.getLogger(__name__)

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

    if not getTargetFSS("TrustManagement"):
        logger.info("trustmanagement.patch: TrustManagement not enabled on target build")
        return None

    return vcsa_utils.getComponentDiscoveryResult(COMPONENT_NAME,
                                                  displayName=_(
                                                   _T("trustmanagement.displayName",
                                                   "TrustManagement Service")))

@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 TrustManagement Service")
    progressReporter = getProgressReporter()
    progressReporter.updateProgress(0, _(_T("trustmanagement.patch.begin",
                                            "Start TrustManagement patching")))
    _do_incremental_patching(ctx)
    progressReporter.updateProgress(100, _(_T("trustmanagement.patch.complete",
                                              "Patching TrustManagement completed")))

def _do_incremental_patching(ctx):
    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))
