"""
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.abspath(os.path.join(curDir, os.pardir))
sys.path.append(parentDir)
import utils

logger = logging.getLogger(__name__)

# Enter Maintenance timeout
ENTER_EMM_TIMEOUT_PATH = 'CoordinatorConfig/Timeouts/EnterMaintenanceModeSeconds'

# Exit Maintenance timeout
EXIT_EMM_TIMEOUT_PATH = 'CoordinatorConfig/Timeouts/ExitMaintenanceModeSeconds'

# compress on roll path
COMPRESS_ON_ROLL_PATH = 'log/compressOnRoll'

# Number of files to backup
MAX_FILE_NUM_PATH = 'log/maxFileNum'

# Size per file
SIZE_IN_MB_PATH = 'log/sizeInMB'

# Max number of hosts for parallel remediation
MAX_HOSTS_FOR_PARALLEL_REMEDIATION_PATH  = 'vci_vcIntegrity/MaxHostsForParallelRemediation'

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

    # Replace the timeout for Enter EMM in the coordinator
    xmlMerger.replace(ENTER_EMM_TIMEOUT_PATH)

    # Replace the timeout for Exit EMM in the coordinator
    xmlMerger.replace(EXIT_EMM_TIMEOUT_PATH)

    # Add new variable to indicate whether to compress the logs after rollover
    xmlMerger.add(COMPRESS_ON_ROLL_PATH)

    # Update the max number of log files to save
    xmlMerger.update(MAX_FILE_NUM_PATH)

    # Update the size of each log file to rollover
    xmlMerger.update(SIZE_IN_MB_PATH)

    # Add new variable to indicate max hosts for parallel remediation
    xmlMerger.add(MAX_HOSTS_FOR_PARALLEL_REMEDIATION_PATH)

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