"""
Copyright 2020 VMware, Inc.  All rights reserved. -- VMware Confidential
"""

import os
import logging
import sys

curDir = os.path.abspath(os.path.dirname(__file__))
parentDir = os.path.join(curDir, "..")
sys.path.append(parentDir)
import utils

logger = logging.getLogger(__name__)

# EHP configurable timeouts
EHP_CONFIG_TIMEOUTS_PATH = 'EhpConfig/Timeouts'

# EHP supported external health providers (wcp, nsx, etc.)
EHP_CONFIG_PROVIDERS_PATH = 'EhpConfig/ExternalProviders'

# Default timeout when waiting for EHP checks has changed
COORDINATOR_EHP_PATH = 'CoordinatorConfig/Timeouts/EhpPerspectivesSeconds'

# Unsupported solutions path
UNSUPPORTED_SOLUTIONS_PATH = "plugins/vci_vapi/UnsupportedSolutions"

# Preload Offline bundles config
PRELOAD_BUNDLE_PATH = "plugins/vci_vapi/preloaded_offline_bundles/bundle"
# Attrib key and value
BUNDLE_PATH_ATTRIB_KEY = 'id'
BUNDLE_PATH_ATTRIB_VALUE = 'WCP'

# HCL config
HCL_CONFIG_PATH = "HclConfig"

# Scale Config
VLCM_SCALE_CONFIG_PATH = "ScaleConfig"

# Coordinator Solutions Configuration
COORDINATOR_CONFIG_SOLUTIONS_PATH = "CoordinatorConfig/Solutions"

def doPatching(ctx):
    logger.info("Patch9_0: being executed %s", ctx)
    # If VUM RPM in source and target build are from same build, then RPM
    # upgrade become a no-op and no new config files copies are generated. If no
    # new config files are present (implying VUM RPM is not updated), then will
    # not execute logic to update the package version.
    if not os.path.exists(utils.UPDATED_INTEGRITY_XML):
        logger.info('%s does not exist. Skip patching integrity config'
                    % utils.UPDATED_INTEGRITY_XML)
        return

    # Patch vci-integrity.xml from vci-integrity.xml.rpmnew
    xmlMerger = utils.XmlMerger(utils.INTEGRITY_XML, \
                                utils.UPDATED_INTEGRITY_XML)

    # Add the wcp bundle under <plugins/vci_vapi/preloaded_offline_bundles>
    xmlMerger.add(PRELOAD_BUNDLE_PATH, \
                  BUNDLE_PATH_ATTRIB_KEY, \
                  BUNDLE_PATH_ATTRIB_VALUE)

    # Add <HclConfig>
    xmlMerger.add(HCL_CONFIG_PATH)

    # Add <ScaleConfig>
    xmlMerger.add(VLCM_SCALE_CONFIG_PATH)

    # Replace <UnsupportedSolutions>
    xmlMerger.replace(UNSUPPORTED_SOLUTIONS_PATH)

    # Add the section for EHP configurable timeouts
    xmlMerger.add(EHP_CONFIG_TIMEOUTS_PATH)

    # Add new EHP supported external health providers
    xmlMerger.replace(EHP_CONFIG_PROVIDERS_PATH)

    # Replace the timeout for EHP checks in the coordinator
    xmlMerger.replace(COORDINATOR_EHP_PATH)

    # Add <CoordinatorConfig><Solutions>
    xmlMerger.add(COORDINATOR_CONFIG_SOLUTIONS_PATH)

    # Save changes into vci-integrity.xml
    xmlMerger.saveToFile()
