"""
Copyright 2019 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__)

# CoordinatorConfig Path
COORDINATOR_CONFIG_PATH = "CoordinatorConfig"
# EHP Config Path
EHP_CONFIG_PATH = "EhpConfig"
# ScanTaskTimeout config
SCAN_TIMEOUT_PATH = "plugins/vci_vapi/ScanTaskTimeoutSeconds"
# Unsupported Solutions config
UNSUPPORTED_SOLUTIONS_PATH = "plugins/vci_vapi/UnsupportedSolutions"
# Preload Offline bundles config
PRELOAD_BUNDLES_PATH = "plugins/vci_vapi/preloaded_offline_bundles"
# Max FDs config
MAX_FDS_PATH = "vmacore/threadPool/MaxFdsPerThread"
# Update depot URL config
ESX_UPDATE_URL_PATH = "HostConfig/ESX4xUpdateUrl"
# HSL config
HSL_CONFIG_PATH = "HslConfig"

def doPatching(ctx):
    logger.info("Patch7_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)

    # Update <CoordinatorConfig>
    xmlMerger.delete(COORDINATOR_CONFIG_PATH, force=True)
    xmlMerger.add(COORDINATOR_CONFIG_PATH)
    # Add <EhpConfig>
    xmlMerger.delete(EHP_CONFIG_PATH, force=True)
    xmlMerger.add(EHP_CONFIG_PATH)
    # Add <plugins/vci_vapi/ScanTaskTimeoutSeconds>
    xmlMerger.delete(SCAN_TIMEOUT_PATH, force=True)
    xmlMerger.add(SCAN_TIMEOUT_PATH)
    # Add <plugins/vci_vapi/UnsupportedSolutions>
    xmlMerger.delete(UNSUPPORTED_SOLUTIONS_PATH, force=True)
    xmlMerger.add(UNSUPPORTED_SOLUTIONS_PATH)
    # Add <plugins/vci_vapi/preloaded_offline_bundles>
    xmlMerger.delete(PRELOAD_BUNDLES_PATH, force=True)
    xmlMerger.add(PRELOAD_BUNDLES_PATH)
    # Add <vmacore/threadPool/MaxFdsPerThread>
    xmlMerger.delete(MAX_FDS_PATH, force=True)
    xmlMerger.add(MAX_FDS_PATH)
    # Replace <HostConfig/ESX4xUpdateUrl>
    xmlMerger.delete(ESX_UPDATE_URL_PATH, force=True)
    xmlMerger.add(ESX_UPDATE_URL_PATH)
    # Add <HslConfig>
    xmlMerger.delete(HSL_CONFIG_PATH, force=True)
    xmlMerger.add(HSL_CONFIG_PATH)

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