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

# enableTelemetry path
ENABLE_TELEMETRY_PATH = "plugins/vci_vapi/enableTelemetry"

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

def patchJettySslConfig():
    # 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_JETTY_VUM_SSL_XML):
        logger.info('%s does not exist. Skip patching jetty ssl config'
                    % utils.UPDATED_JETTY_VUM_SSL_XML)
        return

    # Patch jetty-vum-ssl.xml from jetty-vum-ssl.xml.rpmnew
    xmlMerger = utils.XmlMerger(utils.JETTY_VUM_SSL_XML, utils.UPDATED_JETTY_VUM_SSL_XML)

    # Update value of root's 'class' attribute
    xmlMerger.addOrUpdateRootAttribute('class')

    # Save changes into jetty-vum-ssl.xml
    xmlMerger.saveToFile()

    # Read in the file
    with open(utils.JETTY_VUM_SSL_XML, 'r') as file :
        filedata = file.read()

    # Replace the comment text
    filedata = filedata.replace("SslContextFactory's", "SslContextFactory$Server's")

    # Write the file out again
    with open(utils.JETTY_VUM_SSL_XML, 'w') as file:
        file.write(filedata)

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)

    # Add <enableTelemetry>
    xmlMerger.add(ENABLE_TELEMETRY_PATH)

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

