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

OUTFILE = os.path.join(os.getcwd(),'network.png')
LINK_SPECIFIC = False

try:
  store = yaml.load(open('store.yaml','r'))
except IOError:
  store = {'uptime' : {}, 'snmp' : {}, 'traffic' : {}}
  pass

def pass_filter(host):
  for t in sys.argv:
    if t in host:
       return True
  return False

nodes = {}

def make_graph():
  poel = {}
  link_type = {}
  link_data = {}
  try:
    for host in gformat.get_hostlist():
      # Filter should be proper argument
      if not pass_filter(host):
        continue
      print "## Processing host", host
      datadump = gformat.get_yaml(host)
      nodename = datadump['nodename']
      iface_keys = [elem for elem in datadump.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
      nodes[nodename] = datadump
      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)
        nk = nodename + ':' + datadump[iface_key]['autogen_ifname']
        if poel.has_key(addr): 
          poel[addr] += [nk]
        else: 
          poel[addr] = [nk]
          # Assume all ns_ip to be 11a for a moment
          if datadump[iface_key].has_key('ns_ip'):
            link_type[addr] = '11a'
          else:
            link_type[addr] = datadump[iface_key]['type']

          link_data[addr] = 1
          iface = datadump[iface_key]['autogen_ifname']
          INTERVAL = 60 * 10
          if store['uptime'].has_key(nodename) and store['snmp'].has_key(nodename) and store['traffic'].has_key(nodename):
            if store['traffic'][nodename].has_key(iface):
              (b_in, b_out) = store['traffic'][nodename][iface]
              uptime = store['uptime'][nodename]
              t_kb = float(b_in + b_out) / 1024
              print "# INFO: Found %s kB in %s seconds" % (t_kb, INTERVAL)
              retval = ((t_kb) / uptime) * INTERVAL
              link_data[addr] = retval

          print "### ... %s %s [%s] is of type %s" % (iface, 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 = open('/tmp/test.dot','w')
  sys.stderr.write("# Building temponary graph file\n")
  print >> f, "digraph WirelessLeidenNetwork {"
  print >> f ,"""
graph [ fontsize = 10,
        overlap = scalexy,
        splines = true,
        rankdir = LR,
      ]
node [ fontsize = 10, ]
edge [ fontsize = 10, ]
"""
  for node in sorted(nodes.keys()):
    datadump = nodes[node]
    print "# Processing node:", node
    lines = [node]
    for ik in datadump['autogen_iface_keys']:
      print "# .. ", ik
      if 'alias' in ik or 'wlan' in datadump[ik]['autogen_ifname']:
        continue
      if datadump[ik].has_key('ns_mac'):
        lines.append('<%(autogen_ifname)s> %(bridge_type)s at %(autogen_ifname)s - %(ns_mac)s\\n%(ssid)s\\n%(ns_ip)s' % datadump[ik])
      else:
        lines.append('<%(autogen_ifname)s> %(autogen_ifname)s' % datadump[ik])
    print >> f,"""
"%s" [
shape = "record"
label = "%s"
];
""" % (node, "|".join(lines))


  for addr,leden in poel.iteritems():
    if link_type[addr] == '11a':
      color = 'green'
      weight = 4
    elif link_type[addr] == 'eth':
      color = 'blue'
      weight = 8
    else:
      color = 'black'
      weight = 1
    width = max(1,link_data[addr])
    leden = sorted(set(leden))
    for index,lid in enumerate(leden[:-1]):
      for buur in leden[index + 1:]:
        if LINK_SPECIFIC:
          print >> f,'  %s -> %s [color="%s", weight="%s", style="setlinewidth(%s)"]' % (lid, buur, color, weight, width)
        else:
          print >> f,'  %s -> %s [color="%s", weight="%s", style="setlinewidth(%s)"]' % (lid.split(':')[0], buur.split(':')[0], color, weight, width)
  print >> f, "}"
  f.flush()
  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()

