#!/usr/bin/python


import os, sys, getopt, ConfigParser, logging, commands



def usage(supported):
   print "\n"
   print "glite-wn-info [-c <configfile>] [-h] [-v] -n <name>"
   print "glite-wn-info [--config <configfile>]  [--help] [--verbose] --name <name>"
   print "\t-c <configfile>"
   print "\t\tSpecify a configuration file. Default search path is" 
   print "\t\t/etc/glite-wn-info.conf, $GLITE_LOCATION/etc/glite-wn-info.conf"
   print "\t\tand /opt/glite/etc/glite-wn-info.conf." 
   print "\t-h\tPrint this help."
   print "\t-v\tBe verbose."
   print "\t-n <name>\tA supported value for the WN to return."
   print "\t\t\tOne of:"
   for v in supported:
      print "\t\t\t  -n %s" % v

   print "\nExample: Return the GlueSubClusterUniqueId for this node"
   print "\tglite-wn-info -n GlueSubClusterUniqueId\n"
  

def main():
   # Set Up Defaults
   logging.basicConfig()
   log = logging.getLogger("glite-wn-info") 

   supported = ['GlueSubClusterUniqueId']
   defconfig = ['/etc/glite-wn-info.conf'] 
   if os.environ.get('GLITE_LOCATION'):
      defconfig.append('%s/etc/glite-wn-info.conf' % os.environ['GLITE_LOCATION'])
   defconfig.append('/opt/glite/etc/glite-wn-info.conf') 
   # Move Over the Options
   try:
      opts, args = getopt.getopt(sys.argv[1:], "c:hvn:", ["config=","help","verbose","name="])
   except getopt.GetoptError, err:
      log.exception(str(err))
      usage(supported)
      sys.exit(2)
    

   for o,a in opts:
      if  o in ("-h","--help"):
         usage(supported)
         sys.exit()
      elif o in ("-v","--verbose"):
         log.setLevel(logging.DEBUG)
      elif o in ("-c","--config"):
         conf = a
      elif o in ("-n","--name"):
         name = a
      else:
         assert False, "unhandled option"
 
   # Check the -n flag is set correctly.   
   try:
      name
      supported.index(name)
   except: 
      log.exception("A predefined name must be specified to be retrived with the -n flag.") 
      usage(supported)
      sys.exit(2)

   # Decide which configuration file to use.
   try:
      conf
      config = conf
      log.debug("Using specified configuration file %s." % config)
   except:
     log.debug("Using default search path for configuration file of")
     log.debug(defconfig)
     for f in defconfig:
        log.debug("Looking for file %s" % f)
        if os.path.isfile(f):
           config = f
           log.debug("%s configuration file found and will be used" % config)
           break
        else:
           log.debug("%s configuration file not present" % f)

   try:
      config
   except:
      log.exception("No configuration file could be found")
      usage(supported)
      sys.exit(2)


   # Open the configuation file.

   try:
      cfg = ConfigParser.ConfigParser()
      cfg.readfp(open(config))
   except:
      log.exception("Error opening or parsing %s" % config)
      sys.exit(2)


   try:
      dynamic = cfg.get('dynamic',name) ;
   except:
      log.debug("No dynamic value set for '%s' in configuration file." % name)
   else:
      log.debug("Running dynamic command '%s'" % dynamic)
      (stat,out) = commands.getstatusoutput(dynamic)
      if stat:
         log.debug("Dynamic command '%s' failed with non-zero return code" % dynamic)
      else:
         log.debug("Dynamic value found, '%s', returning it" % out)
         print out
         sys.exit(0)

   try:
      static = cfg.get('static',name) ;
   except:
      log.exception("No static value set for '%s'." % name)
      sys.exit(2)
   else:
      log.debug("Static value present in configuration for '%s'" % name)
      log.debug("Value to be returned is '%s'" % static)
      print static
      sys.exit(0)



# Start the program.
if __name__ == "__main__":
   main()
