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

import os
import logging
import sys

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

logger = logging.getLogger(__name__)

FWP_NS_TAG_PATH = "plugins/vci_vcIntegrity/fwpNameSpace"
FWP_ENABLED_TAG_PATH = "plugins/vci_vcIntegrity/fwpEnabled"
FWP_URL_TAG_PATH = "plugins/vci_vcIntegrity/fwpUrl"
CHECK_VSAN_HEALTH_STATUS_TAG_PATH = "plugins/vci_vcIntegrity/checkVsanHealthStatus"

def doPatching(ctx):
    logger.info("%s: being executed %s", scriptName, ctx)
    patchIntegrityConfig()

def patchIntegrityConfig():
    # 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)

    # Handle 'fwpEnabled' and related config.
    xmlMerger.delete(FWP_ENABLED_TAG_PATH)
    xmlMerger.delete(FWP_URL_TAG_PATH)
    # Order is important! Not 'replace()' because it requires tag to be present
    # in both old and new.
    xmlMerger.delete(FWP_NS_TAG_PATH, force=True)
    xmlMerger.add(FWP_NS_TAG_PATH)

    # Try to delete the tag and add it again
    xmlMerger.delete(CHECK_VSAN_HEALTH_STATUS_TAG_PATH, force=True)
    xmlMerger.add(CHECK_VSAN_HEALTH_STATUS_TAG_PATH)

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