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

This module integrates CertificateManagement patching scripts with the
PatchRunner Framework.

"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017-2019 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

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"),
    ("7","patch_07"),
]

COMPONENT_NAME = "certificatemanagement"

logger = logging.getLogger(__name__)

@extend(Hook.Discovery)
def discover(patch_context):
    if getTargetFSS("NDU_Limited_Downtime") and not vcsa_utils.isDisruptiveUpgrade(patch_context):
        logger.info("no certificatemanagement.patch to apply")
        return None

    logger.info("Executing Discovery Hook for CertificateManagement Service")

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

    return vcsa_utils.getComponentDiscoveryResult(COMPONENT_NAME,
                                                  displayName=_(
                                                   _T("certificatemanagement.displayName",
                                                   "CertificateManagement Service")))


@extend(Hook.Patch)
def execute_patch(patch_context):
    #This hook is invoked after the rpms are installed.
    logger.info("Executing Patch Hook for CertificateManagement Service")
    progressReporter = getProgressReporter()
    progressReporter.updateProgress(0, _(_T("certificatemanagement.patch.begin",
                                            "Start CertificateManagement patching")))
    _do_incremental_patching(patch_context)
    progressReporter.updateProgress(100, _(_T("certificatemanagement.patch.complete",
                                              "Patching CertificateManagement 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))

            utils.update_patch_version(ver)
