#!/usr/bin/python
#######################################################################
# Copyright (C) 2008 VMWare, Inc.
# All Rights Reserved
########################################################################
#
# vib-env
#    get and set environment vars during Vib pre/post scripts,
#    and schedule post-update scripts to be run
#
import sys
import os
import ConfigParser

ESXUPDATEPATH = ['/usr/lib/vmware/python2.4/site-packages']
if os.environ.has_key('ESXUPDATEPATH'):
   ESXUPDATEPATH[0:0] = os.environ['ESXUPDATEPATH'].split(':')
sys.path[0:0] = ESXUPDATEPATH

from vmware.esx45update import const


ESXUPDATE_CONF = const.CONFIGFILE
VIBENV_FILE = const.VIBCONF_FILE


"""
  vib-env varname     - prints value of varname in vib.conf
  vib-env             - prints all vars in vib.conf plus their values
  vib-env varname value  - sets varname to new value, prints out old value

  varname is of the form section.option.  Useful varnames:
  platform.product  - "esx" or "embeddedEsx"
  post-update.*     - values will be sorted by option name and executed
                      after all the Vibs have been installed

  exits with error 1 if there is no value and varname does not exist
  exits with error 2 if any I/O or other error
"""

#
# Parse arguments
#
value = ''
varname = ''
if len(sys.argv) > 2:
   value = ' '.join(sys.argv[2:])
if len(sys.argv) > 1:
   varname = sys.argv[1]
   if len(varname.split('.')) != 2:
      print >>sys.stderr, "varname must be of the form section.option"
      raise SystemExit(1)

#
# Read config file
#
conf = ConfigParser.ConfigParser()
try:
   if os.path.isfile(VIBENV_FILE) and os.path.getsize(VIBENV_FILE) > 0:
      conffile = file(VIBENV_FILE)
   else:
      conffile = file(ESXUPDATE_CONF)
   conf.readfp(conffile)
   conffile.close()
except EnvironmentError, e:
   print >>sys.stderr, "Error reading %s: %s" % (e.filename, e)
   raise SystemExit(2)


#
# vib-env varname:  print out value of varname, error 1 if doesn't exist
# vib-env varname value: print out old value, if varnme exists
#                        if it doesn't, don't print out anything
#                        set value and write vib.conf
#
if varname:
   sect, opt = varname.split('.')
   try:
      oldvalue = conf.get(sect, opt)
   except (ConfigParser.NoSectionError,
           ConfigParser.NoOptionError), e:
      if not value:
         print >>sys.stderr, "No such variable '%s'" % (varname)
         raise SystemExit(1)
   else:
      print oldvalue

   #
   # set new value, write out
   #
   if value:
      if not conf.has_section(sect):
         conf.add_section(sect)
      conf.set(sect, opt, value)
      try:
         if not os.path.isdir(os.path.dirname(VIBENV_FILE)):
            os.makedirs(os.path.dirname(VIBENV_FILE))
         conffile = open(VIBENV_FILE, 'w')
         conf.write(conffile)
         conffile.close()
      except Exception, e:
         print >>sys.stderr, "Error writing %s: %s" % (VIBENV_FILE, e)
         raise SystemExit(2)

else:
   for sect in conf.sections():
      for opt, value in conf.items(sect):
         print "%s.%s = %s" % (sect, opt, value)
# end
