# Copyright 2016 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


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


class XmlParser(ET.XMLParser):
   def __init__(self):
       ET.XMLParser.__init__(self)
       # assumes ElementTree 1.2.X
       self.parser.CommentHandler = self.HandleComment

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


class XmlTree(object):
   def __init__(self, source):
      self.source = source
      self.root = ET.XML(self.source, parser=XmlParser())
      # Create a child-to-parent mapping for the whole tree
      self.cpm = {c: p for p in self.root.iter() for c in p}

   def UnsetPath(self, path):
      text = []

      for match in self.root.findall(path):
         text.append(match.text)

         parent = self.cpm[match]
         children = list(parent)

         if match == children[-1]: # last
            if len(children) > 1: # has siblings
               children[-2].tail = match.tail
            else:
               parent.text = match.tail

         parent.remove(match)

      return text

   def Save(self, output):
      xmlStr = ET.tostring(self.root, encoding='unicode') \
               if IsPython3() else ET.tostring(self.root)

      after = xmlStr.splitlines(True)
      firstLine = after[0]

      for line in self.source.splitlines(True):
         if line == firstLine:
            break
         else:
            output.write(line)

      for line in after:
         output.write(line)

      output.write('\n')


def UnsetXmlPath(xml, path):
   with open(xml, 'r') as f:
      tree = XmlTree(f.read())

   text = tree.UnsetPath(path)

   with open(xml, 'w') as f:
      tree.Save(f)

   return text


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 ResetESXiVPsDisabledProtocols():
   command = ['vim-cmd', 'hostsvc/advopt/update',
              'UserVars.ESXiVPsDisabledProtocols',
              'string', GetESXiVPsDisabledProtocols()]

   subprocess.check_call(command)


def main():
   text = UnsetXmlPath('/etc/vmware/rhttpproxy/config.xml',
                       'vmacore/ssl/sslOptions')
   if text:
      sslOptions = int(text.pop())

      if text:
         sys.exit(1)

      sslOptions = (not sslOptions & 0x4000000, # TLSv1.0
                    not sslOptions & 0x10000000, # TLSv1.1
                    not sslOptions & 0x8000000) # TLSv1.2

      advOption = GetESXiVPsDisabledProtocols().split(',')

      advOption = ('tlsv1' not in advOption,
                   'tlsv1.1' not in advOption,
                   'tlsv1.2' not in advOption)

      if sslOptions != advOption:
         # Make ESX enter reboot required state
         ResetESXiVPsDisabledProtocols()


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


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