# 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
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)

cmt_parser = ET.XMLParser(target=CommentedTreeBuilder())

def IsPython3():
   return int(sys.version[0]) == 3


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

   output = subprocess.check_output(command)

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

      if line.startswith('value'):
         # e.g. value = "sslv3"
         return line.split('=')[1].strip()[1:-1]

   sys.exit(1)


def UpdatevVoldConf(enabled_tls):
   vvoldConfFile = '/etc/vmware/vvold/config.xml'
   tree = ET.parse(vvoldConfFile,parser=cmt_parser)

   #create the necessary xml tags if missing
   if tree.find('vmacore/ssl/protocols') 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'),'protocols')
   tree.find('vmacore/ssl/protocols').text = ','.join(enabled_tls)
   tree.write(vvoldConfFile)


def ConfigurevVold():
   enabled_tls_map = {'tlsv1':'tls1.0','tlsv1.1':'tls1.1','tlsv1.2':'tls1.2'}
   userDisableOptions = GetESXiVPsDisabledProtocols().split(',')
   enabled_tls = [enabled_tls_map.get(x) for x in enabled_tls_map.keys() if x not in userDisableOptions]

   #update the configuration file
   UpdatevVoldConf(enabled_tls)


def main():
   ConfigurevVold()


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

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

