#!/opt/vmware/bin/python
#
# prototype script for getting parameters from visl
#
# Usage: install-parameter parameter default-value
#
# See https://wiki.eng.vmware.com/CloudVM/VislIntegration
#
# Eventually this should be updated to get paramaters from where
# ever visl is grabbing them.
#
# example usage:
#
# install-parameter cm.url https://localhost/cm
#    https://10.17.144.128/cm
#
# The above command assumes that the .vmx file had a key in it like
# guestinfo.cis.cm.url = "https://10.17.144.128/cm"
#

import sys
import os
import logging
from optparse import OptionParser
sys.path.append(os.environ['VMWARE_PYTHON_PATH'])
from appliance.installparamutil import InstallParameters
from cis.utils import setupLogging
from cis.defaults import get_cis_log_dir

def censorValue(key, value):
   """
   Returns censored value ("--CENSORED--") when key appears to be a password
   (i.e., when key contains "password" or "passwd").  Otherwise, return the
   original (uncensored) value.  For example, if the key is "host.passwd",
   "--CENSORED--" is returned.  This function is used to ensure passwords are
   not logged.
   """
   if type(key) == str and ("password" in key or "passwd" in key):
       return "--CENSORED--"
   else:
       return value

def main():
   logDir = os.path.join(get_cis_log_dir(), 'cloudvm')
   setupLogging("install-parameter", logMechanism='file', logDir=logDir)
   parser = OptionParser()
   parser.add_option("-w", "--wait", dest="wait", action='store_true', default=False,
                     help="Wait for the file pointed to by key to be present")
   parser.add_option("-d", "--waitfordefault", dest="waitdefault", action='store_true', default=False,
                     help="Wait for default value for the specified option to exist")
   parser.add_option("-s", "--setdefault", dest="setDefault", default=None,
                     help="Set the default for the specified parameter")
   (options, args) = parser.parse_args()

   try:
      installParams = InstallParameters()
   except IOError, e:
      logging.critical('unable to initialize: %s' % e)
      sys.exit(e)

   key = args[0]
   if options.setDefault != None:
      defval = options.setDefault.decode(sys.stdin.encoding)
      try:
         installParams.setDefault(key, defval)
      except IOError, e:
         # Error writing the new temp file
         logging.critical('Failed to write global default for %s:%s: %s' % \
                          (key, censorValue(key, defval), e))
         sys.exit(e)
      except OSError, e:
         # Error deleting the old default or renaming the new default file
         logging.critical('Failed to replace global default for %s:%s: %s' % \
                          (key, censorValue(key, defval), e))
         sys.exit(e)
      logging.info("Set global default for key '%s' = '%s'" % \
                   (key, censorValue(key, defval)))
   else:
      defval = args[1] if len(args) > 1 else None
      (source,value) = installParams.getParameter(key, defval,
                                                  waitForDefault=options.waitdefault,
                                                  logWaitActions=True)
      if value is None:
         logging.info('No global default and no cmdline default for %s' % key)
         sys.exit(1)
      logging.info("Key '%s' = '%s', source=%s" % \
                   (key, censorValue(key, value), source))
      print value

   sys.exit(0)

if __name__ == "__main__":
    main()
