#
# Copyright 2020 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""PatchRunner integration hook for Infra Profile Service

This module integrates Infra Profile patching scripts with the
PatchRunner Framework.

"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2020 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
import vcsa_utils

sys.path.append(os.path.join(os.path.dirname(__file__), "patches"))

# If a new version is added here, this version has to be updated in:
#    bora/apps/stellar-plugins/infraprofile/infraprofile/
#                   src/main/resources/infraprofile.properties
patches = [
    # In order to update from version 0 (or None - means infraprofile doesn't exist)
    # to version 1, execute patch_01.py
    ("1","patch_01"),
    ("2","patch_02"),
    ("3","patch_03"),
]

COMPONENT_NAME = "infraprofile"

logger = logging.getLogger(__name__)

@extend(Hook.Discovery)
def discover(patch_context):
    logger.info("Executing Discovery Hook for Infra Profile Service")
    return vcsa_utils.getComponentDiscoveryResult(COMPONENT_NAME,
                                                  displayName=_(
                                                   _T("infraprofile.displayName",
                                                   "Infra Profile Service")))

@extend(Hook.Prepatch)
def execute_prePatch(patch_context):
    logger.info("Execute pre patch hook for Infra Profile service")
    # Backup infraprofile.properties file before rpm is installed
    utils.preserve_prop_file(patch_context.stageDirectory)

@extend(Hook.Patch)
def execute_patch(patch_context):
    #This hook is invoked after the rpms are installed.
    logger.info("Executing Patch Hook for Infra Profile Service")
    progressReporter = getProgressReporter()
    progressReporter.updateProgress(0, _(_T("infraprofile.patch.begin",
                                            "Start Infra Profile patching")))
    _do_incremental_patching(patch_context)
    progressReporter.updateProgress(100, _(_T("infraprofile.patch.complete",
                                              "Patching Infra Profile 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(ctx.stageDirectory, ver):
            logger.info("Patch %s needed" % (modulePath))
            mod.doPatching(ctx)
            logger.info('Patch %s applied' % (modulePath))
            utils.update_patch_version(ver)
