# Copyright (c) 2020-2021 VMware, Inc.  All rights reserved.
# -- VMware Confidential

import logging
import shutil
import simpleXml

from l10n import msgMetadata as _T, localizedString as _

logger = logging.getLogger(__name__)

configXml = "/etc/vmware-rhttpproxy/config.xml"
copy = "/etc/vmware-rhttpproxy/config.tmp3"


def getChanges():
    return _(_T("rhttpproxy.patch3.summary",
                "Update 'envoy/L4Filter' config option."))

def changeConfig(filename):
    with open(filename, "r+", encoding="utf-8-sig") as f:
        root = simpleXml.Parse(f.read())

        maxHttpsConn = simpleXml.UnsetPath(root, "envoy/L4Filter/maxHttpsConnections")
        maxHttpConn = simpleXml.UnsetPath(root, "envoy/L4Filter/maxHttpConnections")

        if maxHttpsConn:
            simpleXml.SetText(root, "envoy/L4Filter/maxRemoteHttpsConnections", maxHttpsConn[0])
            simpleXml.SetText(root, "envoy/L4Filter/maxLocalHttpsConnections", maxHttpsConn[0])

        if maxHttpConn:
            simpleXml.SetText(root, "envoy/L4Filter/maxRemoteHttpConnections", maxHttpConn[0])

        simpleXml.SetText(root, "envoy/L4Filter/maxLocalHttpConnections", "12288")

        f.seek(0)
        f.write(simpleXml.Serialize(root))
        f.truncate()

def doPatching(ctx):
    logger.info("Patch03: being executed {0}".format(ctx))
    changeConfig(configXml)

# Must be used during expand phase of NDU
# We also aim to be revertable
def doExpand(ctx):
    logger.info("Patch03: being executed {0}".format(ctx))

    shutil.copyfile(configXml, copy)

    changeConfig(configXml)

def doRevert(ctx):
    logger.info("Patch03: being reverted {0}".format(ctx))
    shutil.copyfile(copy, configXml)