#!/usr/bin/env python
# vim:ts=2:et:sw=2:ai
#
# Build topological network graph
# Rick van der Zwet <info@rickvanderzwet.nl>
import re
import sys
import glob
import tempfile
import subprocess
import gformat

OUTFILE = 'network.png'

def make_graph():
  poel = {}
  link_type = {}
  try:
    for host in gformat.get_hostlist():
      print "## Processing host", host
      datadump = gformat.get_yaml(host)
      iface_keys = [elem for elem in datadump.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
      for iface_key in iface_keys:
        l = datadump[iface_key]['ip']
        addr, mask = l.split('/')

        # Not parsing of these folks please
        if not gformat.valid_addr(addr):
          continue

        addr = gformat.parseaddr(addr)
        mask = int(mask)
        addr = addr & ~((1 << (32 - mask)) - 1)
        if poel.has_key(addr): 
          poel[addr] += [host]
        else: 
          poel[addr] = [host]
          # Assume all eth2wifibridge to be 11a for a moment
          if datadump[iface_key].has_key('eth2wifibridge'):
            link_type[addr] = '11a'
          else:
            link_type[addr] = datadump[iface_key]['type']
          print "### %s [%s] is of type %s" % (gformat.showaddr(addr), iface_key, link_type[addr])
  except (KeyError, ValueError), e:
    print "[FOUT] in '%s' interface '%s'" % (host,iface_key) 
    print e
    sys.exit(1)

  f = tempfile.NamedTemporaryFile(bufsize=0)
  sys.stderr.write("# Building temponary graph file\n")
  print >> f, "Graph WirelessLeidenNetwork {"
  print >> f ,"""
graph [ fontsize = 36,
        overlap = scalexy,
        splines = true,
      ]
"""
  for addr,leden in poel.iteritems():
    if link_type[addr] == '11a':
      color = 'red'
      weight = 4
    elif link_type[addr] == 'eth':
      color = 'blue'
      weight = 8
    else:
      color = 'black'
      weight = 1
    leden = sorted(set(leden))
    for index,lid in enumerate(leden[:-1]):
      for buur in leden[index + 1:]:
        print >> f,'  %s -- %s [label="%s", color="%s", weight="%s"]' % (lid, buur, gformat.showaddr(addr), color, weight)
  print >> f, "}"
  sys.stderr.write("# Plotting temponary graph file using graphviz\n")
  retval = subprocess.call(["neato","-Tpng",f.name, "-o", OUTFILE])
  if retval != 0:
    sys.stderr.write("# FAILED [%i]\n" % retval)
    subprocess.call(["cat",f.name])
    exit(1)
  sys.stderr.write("# COMPLETED find your output in %s\n" % OUTFILE)
    

if __name__ == "__main__":
  make_graph()

