# Copyright 2017 VMware, Inc.  All rights reserved. -- VMware Confidential

/bin/python -c  "

# In Python3 ET.XMLParser is overwritten in xml.etree.ElementTree.py
# when the _elementtree module is loaded which we think is incorrect.
# Therefore we create an empty _elementtree module in order to cheat Python
# that it's already loaded.

import imp
import sys
import re
sys.modules['_elementtree'] = imp.new_module('_elementtree')

import subprocess
import xml.etree.ElementTree as ET

class CommentedTreeBuilder(ET.TreeBuilder):
    def __init__(self, *args, **kwargs):
        super(CommentedTreeBuilder, self).__init__(*args, **kwargs)

    def comment(self, data):
        self.start(ET.Comment, {})
        self.data(data)
        self.end(ET.Comment)


def GetESXiVPsAllowedCiphers():
   command = ['vim-cmd', 'hostsvc/advopt/view',
              'UserVars.ESXiVPsAllowedCiphers']

   output = subprocess.check_output(command)

   for line in output.decode('ascii').split('\n'):
      line = line.strip()

      if line.startswith('value'):
         # e.g. value = "ECDHE-RSA-AES256-SHA384"
         return line.split('=')[1].strip()[1:-1]
   sys.exit(1)


def UpdateXml(config_file):
   cipher_suite = GetESXiVPsAllowedCiphers()
   tree = ET.parse(config_file,parser=ET.XMLParser(target=CommentedTreeBuilder()))

   #create the necessary xml tags if missing
   if tree.find('vmacore/ssl/cipherList') is None:
      vmacore_tag = tree.find('vmacore')
      if tree.find('vmacore/ssl') is None:
         ssl_tag = ET.SubElement(vmacore_tag,'ssl')
      ET.SubElement(tree.find('vmacore/ssl'),'cipherList')
   tree.find('vmacore/ssl/cipherList').text = cipher_suite
   tree.write(config_file)


def updateText(config_file, key_name):
   cipher_suite = GetESXiVPsAllowedCiphers()
   with open(config_file) as f:
      s = f.read()
      if key_name == 'sslCipherList':
         new_line = \"sslCipherList\" + ': ' + \"\\\"\" + cipher_suite + \"\\\"\"
      elif key_name == 'tls.ciphers':
         new_line = \"tls.ciphers = \" + \"\\\"\" + cipher_suite + \"\\\"\"

      if key_name not in s:
         subprocess.call([\"sed\", \"-i\", \"-e\", \"\$ a \" + new_line, config_file])
      else:
         sed_cmd = \"s/^\" + key_name + \".*/\" + new_line + \"/g\"
         print(sed_cmd)
         subprocess.call([\"sed\", \"-i\", \"-e\", sed_cmd, config_file])


def ConfigureCiphers():
   rhttpproxy_conf = '/etc/vmware/rhttpproxy/config.xml'
   fdm_conf = '/etc/opt/vmware/fdm/fdm.cfg'
   hostd_conf = '/etc/vmware/hostd/config.xml'
   vpxa_conf = '/etc/vmware/vpxa/vpxa.cfg'
   sfcbd_conf = '/etc/sfcb/sfcb.cfg'
   authd_conf = '/etc/vmware/config'

   UpdateXml(rhttpproxy_conf)
   UpdateXml(fdm_conf)
   UpdateXml(hostd_conf)
   UpdateXml(vpxa_conf)
   updateText(sfcbd_conf, 'sslCipherList')
   updateText(authd_conf, 'tls.ciphers')

def main():
   ConfigureCiphers()


if __name__ == '__main__':
   main()
"

# Backup all modified files in /etc
/sbin/backup.sh 0
