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


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 ChangeSFCBConfigData(tsl_keyword, config_string, config_data ):
   matchingStringList = [line for line in config_data if tsl_keyword in line]
   if len(matchingStringList) > 0:
      config_data.remove(matchingStringList[0])
   config_data.append(config_string)
   return config_data


def ConfigureSFCB():
   userDisableOptions = GetESXiVPsDisabledProtocols().split(',')
   sfcbConfFile  = '/etc/sfcb/sfcb.cfg'

   sslv3String = 'enableSSLv3: true\n'
   tlsv10String = 'enableTLSv1: true\n'
   tlsv11String = 'enableTLSv1_1: true\n'
   tlsv12String = 'enableTLSv1_2: true\n'

   if 'sslv3' in userDisableOptions:
      sslv3String = 'enableSSLv3: false\n'
   if 'tlsv1' in userDisableOptions:
      tlsv10String = 'enableTLSv1: false\n'
   if 'tlsv1.1' in userDisableOptions:
      tlsv11String = 'enableTLSv1_1: false\n'
   if 'tlsv1.2' in userDisableOptions:
      tlsv12String = 'enableTLSv1_2: false\n'

   with open(sfcbConfFile) as inputFile:
      sfcbConfig = inputFile.readlines()

   sfcbConfig = ChangeSFCBConfigData('enableSSLv3', sslv3String, sfcbConfig)
   sfcbConfig = ChangeSFCBConfigData('enableTLSv1', tlsv10String, sfcbConfig)
   sfcbConfig = ChangeSFCBConfigData('enableTLSv1_1', tlsv11String, sfcbConfig)
   sfcbConfig = ChangeSFCBConfigData('enableTLSv1_2', tlsv12String, sfcbConfig)

   with open(sfcbConfFile, 'w+') as outFile:
      outFile.write(''.join(sfcbConfig))

def main():
   ConfigureSFCB()


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

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