Index: /nodes/gformat.py
===================================================================
--- /nodes/gformat.py	(revision 8266)
+++ /nodes/gformat.py	(revision 8267)
@@ -5,4 +5,6 @@
 # Rick van der Zwet <info@rickvanderzwet.nl>
 import cgi
+import cgitb
+import copy
 import glob
 import os
@@ -17,4 +19,5 @@
 __version__ = '$Id$'
 
+
 files = [ 
     'authorized_keys',
@@ -27,8 +30,26 @@
 
 
-def print_title(nodelist):
+def get_proxylist():
+  """Get all available proxies proxyX sorting based on X number"""
+  os.chdir(NODE_DIR)
+  proxylist = sorted(glob.glob("proxy*"),
+                key=lambda name: int(''.join([c for c in name if c in string.digits])),
+                cmp=lambda x,y: x - y)
+  return proxylist
+
+
+
+def get_nodelist():
+  """ Get all available nodes - sorted """
+  os.chdir(NODE_DIR)
+  nodelist = sorted(glob.glob("CNode*"))
+  return nodelist
+
+
+
+def generate_title(nodelist):
   """ Main overview page """
   items = {'root' : "." } 
-  print """
+  output = """
 <html>
   <head>
@@ -53,10 +74,10 @@
   for node in sorted(nodelist):
     items['node'] = node
-    print '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
+    output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
     for config in files:
       items['config'] = config
-      print '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
-    print "</tr>"
-  print """
+      output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
+    output += "</tr>"
+  output += """
     </table>
     <hr />
@@ -67,9 +88,11 @@
   """ % __version__
 
-
-
-def print_node(node):
+  return output
+
+
+
+def generate_node(node):
   """ Print overview of all files available for node """
-  print "\n".join(files)
+  return "\n".join(files)
 
 
@@ -249,4 +272,14 @@
 
 
+def write_yaml(item, datadump):
+  """ Write configuration yaml for 'item'"""
+  gfile = NODE_DIR + '/%s/wleiden.yaml' % item
+
+  f = open(gfile, 'w')
+  f.write(format_wleiden_yaml(datadump))
+  f.close()
+
+
+
 def generate_resolv_conf(datadump):
   """ Generate configuration file '/etc/resolv.conf' """
@@ -261,11 +294,5 @@
 """ % datadump
   
-  # proxyX sorting based on X number
-  os.chdir(NODE_DIR)
-  proxies = sorted(glob.glob("proxy*"),
-              key=lambda name: int(''.join([c for c in name if c in string.digits])),
-              cmp=lambda x,y: x - y)
-
-  for proxy in proxies:
+  for proxy in get_proxylist():
     proxy_ip = get_yaml(proxy)['masterip']
     output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
@@ -274,13 +301,22 @@
 
 
-def generate_wleiden_yaml(datadump):
+def format_yaml_value(value):
+  """ Get yaml value in right syntax for outputting """
+  if isinstance(value,str):
+    output = "'%s'" % value
+  else:
+    output = value
+  return output 
+
+
+
+def format_wleiden_yaml(datadump):
   """ Special formatting to ensure it is editable"""
-  output = generate_header("#")
-  output += "# Genesis config yaml style\n" 
+  output = "# Genesis config yaml style\n" 
   output += "# vim:ts=2:et:sw=2:ai\n"
   output += "#\n"
   iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
   for key in sorted(set(datadump.keys()) - set(iface_keys)):
-    output += "%s: %s\n" % (key, datadump[key])
+    output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
   
   output += "\n\n"
@@ -289,6 +325,5 @@
     output += "%s:\n" % iface_key
     for key in sorted(datadump[iface_key]):
-      #output += yaml.dump(datadump[iface_key], default_flow_style=False)
-      output += "  %s: %s\n" % (key, datadump[iface_key][key]) 
+      output += "  %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key])) 
     output += "\n\n"
 
@@ -297,34 +332,43 @@
 
 
-def print_config(node, config):
+def generate_wleiden_yaml(datadump):
+  """ Generate (petty) version of wleiden.yaml"""
+  output = generate_header("#")
+  output += format_wleiden_yaml(datadump)
+  return output
+
+
+
+def generate_config(node, config):
   """ Print configuration file 'config' of 'node' """
+  output = ""
   try:
     # Load config file
     datadump = get_yaml(node)
     
+    # Preformat certain needed variables for formatting and push those into special object
+    datadump_extra = copy.deepcopy(datadump)
+    if not datadump_extra.has_key('domain'):
+      datadump_extra['domain'] = 'wleiden.net'
+    datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
+    datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
+
     if config == 'wleiden.yaml':
-      print generate_wleiden_yaml(datadump)
-      return
-
-    # Preformat certain needed variables for formatting
-    if not datadump.has_key('domain'):
-      datadump['domain'] = 'wleiden.net'
-    datadump['nodename_lower'] = datadump['nodename'].lower()
-    datadump['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
-
-    if config == 'authorized_keys':
+      output += generate_wleiden_yaml(datadump)
+    elif config == 'authorized_keys':
       f = open("global_keys", 'r')
-      print f.read()
+      output += f.read()
       f.close()
     elif config == 'dnsmasq.conf':
-      print generate_dnsmasq_conf(datadump)
+      output += generate_dnsmasq_conf(datadump_extra)
     elif config == 'rc.conf.local':
-      print generate_rc_conf_local(datadump)
+      output += generate_rc_conf_local(datadump_extra)
     elif config == 'resolv.conf':
-      print generate_resolv_conf(datadump)
+      output += generate_resolv_conf(datadump_extra)
     else:
       assert False, "Config not found!"   
   except IOError, e:
-    print "[ERROR] Config file not found"
+    output += "[ERROR] Config file not found"
+  return output
 
 
@@ -342,20 +386,19 @@
     sys.exit(0)
   
-  os.chdir(NODE_DIR)
-  nodelist = glob.glob("CNode*")
   
   uri = os.environ['PATH_INFO'].strip('/').split('/')
+  output = ""
   if not uri[0]:
-    print "Content-type:text/html\r\n\r\n",
-    print_title(nodelist)
+    output += "Content-type:text/html\r\n\r\n"
+    output += generate_title(get_nodelist())
   elif len(uri) == 1:
-    print "Content-type:text/plain\r\n\r\n",
-    print_node(uri[0])
+    output += "Content-type:text/plain\r\n\r\n"
+    output += generate_node(uri[0])
   elif len(uri) == 2:
-    print "Content-type:text/plain\r\n\r\n",
-    print_config(uri[0], uri[1])
+    output += "Content-type:text/plain\r\n\r\n"
+    output += generate_config(uri[0], uri[1])
   else:
     assert False, "Invalid option"
-
+  print output
 
 
@@ -371,39 +414,46 @@
 
 
-# Allow easy hacking using the CLI
-if not os.environ.has_key('PATH_INFO'):
-  if len(sys.argv) < 2:
-    usage()
-
-  if sys.argv[1] == "standalone":
-    import SocketServer
-    import CGIHTTPServer
-    try:
-      PORT = int(sys.argv[2])
-    except (IndexError,ValueError):
-      PORT = 8000
-
-    class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
-      """ Serve this CGI from the root of the webserver """
-      def is_cgi(self):
-        if "favicon" in self.path:
-          return False
-
-        self.cgi_info = (__file__, self.path)
-        self.path = ''
-        return True
-    handler = MyCGIHTTPRequestHandler
-    httpd = SocketServer.TCPServer(("", PORT), handler)
-    httpd.server_name = 'localhost'
-    httpd.server_port = PORT
+def main():
+  """Hard working sub"""
+  # Allow easy hacking using the CLI
+  if not os.environ.has_key('PATH_INFO'):
+    if len(sys.argv) < 2:
+      usage()
+  
+    if sys.argv[1] == "standalone":
+      import SocketServer
+      import CGIHTTPServer
+      try:
+        PORT = int(sys.argv[2])
+      except (IndexError,ValueError):
+        PORT = 8000
+  
+      class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
+        """ Serve this CGI from the root of the webserver """
+        def is_cgi(self):
+          if "favicon" in self.path:
+            return False
+  
+          self.cgi_info = (__file__, self.path)
+          self.path = ''
+          return True
+      handler = MyCGIHTTPRequestHandler
+      httpd = SocketServer.TCPServer(("", PORT), handler)
+      httpd.server_name = 'localhost'
+      httpd.server_port = PORT
+      
+      print "serving at port", PORT
+      httpd.serve_forever()
+    elif sys.argv[1] == "test":
+      os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
+      os.environ['SCRIPT_NAME'] = __file__
+      process_cgi_request()
+    else:
+      usage()
+  else:
+    cgitb.enable()
+    process_cgi_request()
     
-    print "serving at port", PORT
-    httpd.serve_forever()
-  elif sys.argv[1] == "test":
-    os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
-    os.environ['SCRIPT_NAME'] = __file__
-    process_cgi_request()
-  else:
-    usage()
-else:
-  process_cgi_request()
+
+if __name__ == "__main__":
+  main()
