filter out invalid python path
[sfa.git] / geni-config-tty
1 #!/usr/bin/python
2
3 # Interactively prompts for variable values
4 # expected arguments are
5 # command -d [default-xml [custom-xml [ consolidated-xml ]]]
6 #
7 # -d is for the myplc-devel package
8
9 # we use 3 instances of PLCConfiguration throughout:
10 # cdef : models the defaults, from plc_default.xml
11 # cread : merged from plc_default & configs/site.xml
12 # cwrite : site.xml + pending changes
13
14 import sys
15 import os
16 import re
17 import readline
18 import traceback
19 from optparse import OptionParser
20
21 from geni.util.config import Config
22
23 usual_variables = ["GENI_REGISTRY_ROOT_AUTH",
24                    "GENI_REGISTRY_LEVEL1_AUTH",
25                    "GENI_REGISTRY_ENABLED",
26                    "GENI_REGISTRY_HOST", 
27                    "GENI_REGISTRY_PORT",
28                    "GENI_AGGREGATE_ENABLED",
29                    "GENI_AGGREGATE_HOST",
30                    "GENI_AGGREGATE_PORT",
31                    "GENI_SM_ENABLED",
32                    "GENI_SM_HOST",
33                    "GENI_SM_PORT",
34                    "GENI_PLC_USER",
35                    "GENI_PLC_PASSWORD",    
36                    "GENI_PLC_HOST",
37                    "GENI_PLC_PORT",
38                    "GENI_PLC_API_PATH"
39                    ]
40
41
42 mainloop_usage= """Available commands:
43  Uppercase versions give variables comments, when available
44  u/U\t\t\tEdit usual variables
45  w/W\t\t\tWrite / Write & reload
46  q\t\t\tQuit (without saving)
47  h/?\t\t\tThis help
48 ---
49  l/L [<var>]\tShow Locally modified variables/values
50  s/S [<var>]\tShow variables/values (all, in category, single)
51  e/E [<var>]\tEdit variables (all, in category, single)
52 ---
53 """ 
54
55 command_usage="%prog [options]"
56 command_usage += """
57   Unless you specify the -d option, meaning you want to configure
58   myplc-devel instead of regular myplc, in which case""" 
59
60 variable_usage= """Edit Commands :
61 .\tStops prompting, return to mainloop
62 =\tShows default value
63 ?\tThis help
64 """
65
66 def save(changes, config_file):
67
68     print "save"
69
70 def get_defaults():
71     geni_config = Config()
72     plc_vars = {'PLC_API_MAINTENANCE_PASSWORD': 'GENI_PLC_PASSWORD',
73                 'PLC_API_MAINTENCE_USER': 'GENI_PLC_PASSWORD'
74                }
75     try:
76         from geni.util.config import plcConfig
77         plc_config = plcConfig
78     except:
79         plc_config = None
80     
81     defaults = {}
82     for var in dir(geni_config):
83         if var.startswith('GENI'):
84             value = eval("geni_config.%s" % var)
85             defaults[var] = value
86
87     # some defaults come from plc_config
88     for var in dir(plc_config):
89         if var in plc_vars:
90             value = eval("plc_config.%s" % var)
91             defaults[plc_vars[var]] = value
92
93     return defaults       
94
95 def prompt_variable(variable, default_config):
96     if variable in default_config:
97         default_value = default_config[variable]
98     else:
99         default_value = ""  
100    
101     while True:
102         prompt = "%(variable)s : [%(default_value)s] " % locals()
103         try: 
104             answer = raw_input(prompt).strip()
105         except EOFError:
106             raise Exception ('BailOut')
107         except KeyboardInterrupt:
108             print "\n"
109             raise Excception ('BailOut')
110
111         if (answer == "") or (answer == default_value):
112             return answer
113         elif (answer == "."):
114             raise Exception ('BailOut')
115         elif (answer == "?"):
116             print variable_usage.strip()
117         elif (answer == "="):
118             print ("%s defaults to %s" %(variable,default_value))
119         else:
120             return answer        
121     
122 def mainloop (default_config, config_file):
123     changes = {}
124     while True:
125         try:
126             answer = raw_input("Enter command (u for usual changes, w to save, ? for help) ").strip()
127         except EOFError:
128             answer =""
129         except KeyboardInterrupt:
130             print "\nBye"
131             sys.exit()
132
133         if (answer == "") or (answer in "?hH"):
134             print mainloop_usage
135             continue
136         if answer in ['?']:
137             print "help"  
138
139         if (answer in ["q","Q"]):
140             # todo check confirmation
141             return
142         elif (answer == "w"):
143             save(changes, config_file)
144         elif (answer == "u"):
145             try: 
146                 for varname in usual_variables:
147                     changes[varname] = prompt_variable(varname, default_config)
148             except Exception, inst:
149                 if (str(inst) != 'BailOut'):
150                     raise
151         elif (answer in ["e","E"]):
152             try:
153                 prompt_variable (cdef,cread,cwrite,category,variable,
154                                  show_comments,False)
155             except Exception, inst:
156                 if (str(inst) != 'BailOut'):
157                     raise
158         elif (answer in "vVsSlL"):
159             pass
160             #show_variable (c1,c2,c3,category,variable,show_value,show_comments)
161         else:
162             print ("Unknown command >%s< -- use h for help" % answer)
163
164 ####################
165 def main ():
166
167     command=sys.argv[0]
168     argv = sys.argv[1:]
169     save = True
170     parser = OptionParser(usage=command_usage, version="%prog 1.0")
171     parser.set_defaults(config_dir="/etc/geni",
172                         usual_variables=[])
173     parser.add_option("","--configdir",dest="config_dir",help="specify configuration directory")
174     parser.add_option("","--usual_variable",dest="usual_variables",action="append", help="add a usual variable")
175
176     (config,args) = parser.parse_args()
177     if len(args)>3:
178         parser.error("too many arguments")
179
180     config_dir = parser.values.config_dir
181     config_file = os.sep.join([config_dir, 'geni_config'])
182     defaults = get_defaults()
183     mainloop (defaults, config_file)
184     return 0
185
186 if __name__ == '__main__':
187     main()