added --extractgids, --dumpparents
[sfa.git] / geni-config-tty
index 7a5df8a..cf39986 100755 (executable)
@@ -19,11 +19,14 @@ import traceback
 from optparse import OptionParser
 
 from geni.util.config import Config
+from geni.util.hierarchy import *
+from geni.util.misc import *
+
 
 usual_variables = ["GENI_REGISTRY_ROOT_AUTH",
                    "GENI_REGISTRY_LEVEL1_AUTH",
                    "GENI_REGISTRY_ENABLED",
-                   "GENI_REGISTRY_HOST" 
+                   "GENI_REGISTRY_HOST", 
                    "GENI_REGISTRY_PORT",
                    "GENI_AGGREGATE_ENABLED",
                    "GENI_AGGREGATE_HOST",
@@ -40,14 +43,13 @@ usual_variables = ["GENI_REGISTRY_ROOT_AUTH",
 
 
 mainloop_usage= """Available commands:
- Uppercase versions give variables comments, when available
  u/U\t\t\tEdit usual variables
  w/W\t\t\tWrite / Write & reload
  q\t\t\tQuit (without saving)
  h/?\t\t\tThis help
 ---
  l/L [<var>]\tShow Locally modified variables/values
- s/S [<var>]\tShow variables/values (all, in category, single)
+ s/S [<var>]\tShow all current variables/values 
  e/E [<var>]\tEdit variables (all, in category, single)
 ---
 """ 
@@ -55,24 +57,74 @@ mainloop_usage= """Available commands:
 command_usage="%prog [options]"
 command_usage += """
   Unless you specify the -d option, meaning you want to configure
-  myplc-devel instead of regular myplc, in which case""" 
+  using defaults without interactive prompts""" 
 
 variable_usage= """Edit Commands :
-#\tShow variable comments
 .\tStops prompting, return to mainloop
-/\tCleans any site-defined value, reverts to default
 =\tShows default value
->\tSkips to next category
-?\tThis help
+?\tThis help    
 """
 
-def save():
-    print "save"
+def save_config(changes, config_file):
+    # always validate before saving
+    changes = validate(changes) 
+    
+    cfile = open(config_file, 'r')
+    lines = cfile.readlines()
+    newlines = []
+    cfile.close()
+    for line in lines:
+        added = False
+        for variable in changes:
+            if line.startswith(variable):
+                try:
+                    value = int(changes[variable])
+                    newline = '%s=%s\n' % (variable, value)
+                    newlines.append(newline)
+                except:
+                    value = changes[variable]
+                    newline = '%s="%s"\n' % (variable, value)
+                    newlines.append(newline)
+                added = True
+                break
+        if not added:
+            newlines.append(line) 
+    
+    cfile = open(config_file, 'w')
+    cfile.writelines(newlines)
+    cfile.close()
+
+def validate(changes):
+    defaults = get_defaults()
+    
+    if not changes:
+        return
+
+    # GENI_INTERFACE_HRN is GENI_REGISTRY_LEVEL1_AUTH, if thats blank it
+    # then defaults to GENI_REGISTRY_ROOT_AUTH 
+    # GENI_REGISTRY_LEVEL1_AUTH, so if either of these are present we must 
+    # update GENI_INTERFACE_HRN
+    if 'GENI_REGISTRY_ROOT_AUTH' in changes:
+        root_auth = changes['GENI_REGISTRY_ROOT_AUTH']
+    else:
+        root_auth = defaults['GENI_REGISTRY_ROOT_AUTH']
+             
+    if 'GENI_REGISTRY_LEVEL1_AUTH' in changes:
+        level1_auth = changes['GENI_REGISTRY_LEVEL1_AUTH']
+    else:
+        level1_auth = default['GENI_REGISTRY_LEVEL1_AUTH']
+                
+    if level1_auth:
+        interface_hrn = level1_auth
+    else:
+        interface_hrn = root_auth
+    changes['GENI_INTERFACE_HRN'] = interface_hrn
+    return changes                            
 
 def get_defaults():
     geni_config = Config()
     plc_vars = {'PLC_API_MAINTENANCE_PASSWORD': 'GENI_PLC_PASSWORD',
-                'PLC_API_MAINTENCE_USER': 'GENI_PLC_PASSWORD'
+                'PLC_API_MAINTENANCE_USER': 'GENI_PLC_USER'
                }
     try:
         from geni.util.config import plcConfig
@@ -99,9 +151,34 @@ def prompt_variable(variable, default_config):
         default_value = default_config[variable]
     else:
         default_value = ""  
-   #while True:
+   
+    while True:
+        prompt = "%(variable)s : [%(default_value)s] " % locals()
+        try: 
+            answer = raw_input(prompt).strip()
+        except EOFError:
+            raise Exception ('BailOut')
+        except KeyboardInterrupt:
+            print "\n"
+            raise Excception ('BailOut')
+
+        if (answer == "") or (answer == default_value):
+            return default_value
+        elif answer in ['""', "''"]:
+            return ""
+        elif (answer == "."):
+            raise Exception ('BailOut')
+        elif (answer == "?"):
+            print variable_usage.strip()
+        elif (answer == "="):
+            print ("%s defaults to %s" %(variable,default_value))
+        else:
+            return answer
+
+def show_variable(variable, value_dict):
+    print "%s=%s" % (variable, value_dict[variable])                    
     
-def mainloop (default_config):
+def mainloop (default_config, config_file):
     changes = {}
     while True:
         try:
@@ -119,14 +196,12 @@ def mainloop (default_config):
             print "help"  
 
         if (answer in ["q","Q"]):
-            # todo check confirmation
             return
         elif (answer == "w"):
-            save()
+            save_config(changes, config_file)
         elif (answer == "u"):
             try: 
                 for varname in usual_variables:
-                    print varname
                     changes[varname] = prompt_variable(varname, default_config)
             except Exception, inst:
                 if (str(inst) != 'BailOut'):
@@ -138,12 +213,54 @@ def mainloop (default_config):
             except Exception, inst:
                 if (str(inst) != 'BailOut'):
                     raise
-        elif (command in "vVsSlL"):
-            pass
-            #show_variable (c1,c2,c3,category,variable,show_value,show_comments)
+        elif (answer in "sS"):
+            for varname in usual_variables:
+                show_variable (varname, default_config)
+        elif (answer in "lL"):
+            if not changes:
+                print "No changes to display"
+            else:
+                for varname in changes:
+                    show_variable(varname, changes)
         else:
             print ("Unknown command >%s< -- use h for help" % answer)
 
+    result = {}
+    result.update(defaults)
+    result.update(changes)
+    return result
+    
+def setup_server_key(config_dict):
+    hrn = config_dict.get('GENI_INTERFACE_HRN')
+    print "updating server key ...", 
+    if not hrn: print "nothing to do"
+   
+    # Get the path to the authorities directory hierarchy
+    hierarchy = Hierarchy()
+    path = hierarchy.basedir
+    auth_path = hrn.replace(".", os.sep)
+    # define some useful variables   
+    key = 'server.key'
+    cert = 'server.cert'
+    hrn_leaf = get_leaf(hrn)
+    if not hrn_leaf:
+        hrn_leaf = hrn
+    new_server_key = os.sep.join([path, auth_path, hrn_leaf])
+    old_server_key = os.sep.join([path, key])
+    old_server_cert = os.sep.join([path, cert])
+
+    # remove old key/cert
+    for fd in [old_server_key, old_server_cert]:
+        if os.path.isfile(fd):
+            os.remove(fd)
+
+    # create new server.key
+    #os.copy(new_server_key, old_server_key)
+    print "%(old_server_key)s copied from %(new_server_key)s" % locals()
+    
+    
+
 ####################
 def main ():
 
@@ -153,15 +270,23 @@ def main ():
     parser = OptionParser(usage=command_usage, version="%prog 1.0")
     parser.set_defaults(config_dir="/etc/geni",
                         usual_variables=[])
-    parser.add_option("","--configdir",dest="config_dir",help="specify configuration directory")
+    parser.add_option("","--configdir",dest="config_dir",action="append", help="specify configuration directory")
     parser.add_option("","--usual_variable",dest="usual_variables",action="append", help="add a usual variable")
-
+    parser.add_option("-d", "--default", action="count", help="dont prompt for values, just use defaults")
     (config,args) = parser.parse_args()
     if len(args)>3:
         parser.error("too many arguments")
 
+    config_dir = parser.values.config_dir
+    config_file = os.sep.join([config_dir, 'geni_config'])
     defaults = get_defaults()
-    mainloop (defaults)
+    # if -d is specified dont prompt, just configure with defaults
+    if '-d' in argv:
+        save_config(defaults, config_file)
+        results = defaults
+    else:        
+        results = mainloop (defaults, config_file)
+    setup_server_key(results)
     return 0
 
 if __name__ == '__main__':