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

import logging
import shutil
import simpleXml
import yaml

from l10n import msgMetadata as _T, localizedString as _

logger = logging.getLogger(__name__)

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

def getChanges():
    return _(_T("rhttpproxy.patch2.summary",
                "Transfer options from Envoy's config.yaml to Envoy ADS config.xml"))

def changeConfig(filename):
    with open('/etc/vmware-envoy/config.yaml') as config_file:
       config = yaml.safe_load(config_file)
       if config.get("vmware") is not None:
          envoyVMWopts = config["vmware"]
          logger.info("{0}".format(envoyVMWopts))
          with open(filename, "r+", encoding="utf-8-sig") as f:
              root = simpleXml.Parse(f.read())
              if envoyVMWopts.get("max_https_connections") is not None:
                  logger.info("Transfering maxHttpsConnections")
                  simpleXml.SetText(root, "envoy/L4Filter/maxHttpsConnections", str(envoyVMWopts["max_https_connections"]))

              if envoyVMWopts.get("max_http_connections") is not None:
                  logger.info("Transfering maxHttpConnections")
                  simpleXml.SetText(root, "envoy/L4Filter/maxHttpConnections", str(envoyVMWopts["max_http_connections"]))

              if envoyVMWopts.get("new_https_connection_timeout") is not None:
                  logger.info("Transfering newHttpsConnectionTimeoutMs")
                  simpleXml.SetText(root, "envoy/L4Filter/newHttpsConnectionTimeoutMs", str(envoyVMWopts["new_https_connection_timeout"]))

              if envoyVMWopts.get("new_http_connection_timeout") is not None:
                  logger.info("Transfering newHttpConnectionTimeoutMs")
                  simpleXml.SetText(root, "envoy/L4Filter/newHttpConnectionTimeoutMs", str(envoyVMWopts["new_http_connection_timeout"]))

              if envoyVMWopts.get("tcp_keepalive_probes") is not None:
                  logger.info("Transfering tcpKeepAliveNumProbes")
                  simpleXml.SetText(root, "envoy/L4Filter/tcpKeepAliveNumProbes", str(envoyVMWopts["tcp_keepalive_probes"]))

              if envoyVMWopts.get("tcp_keepalive_time") is not None:
                  logger.info("Transfering tcpKeepAliveTimeSec")
                  simpleXml.SetText(root, "envoy/L4Filter/tcpKeepAliveTimeSec", str(envoyVMWopts["tcp_keepalive_time"]))

              if envoyVMWopts.get("tcp_keepalive_interval") is not None:
                  logger.info("Transfering tcpKeepAliveIntervalSec")
                  simpleXml.SetText(root, "envoy/L4Filter/tcpKeepAliveIntervalSec", str(envoyVMWopts["tcp_keepalive_interval"]))

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

def doPatching(ctx):
    logger.info("Patch02: 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("Patch02: being executed {0}".format(ctx))

    shutil.copyfile(configXml, copy)

    changeConfig(configXml)

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