#!/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

import urllib
import re
import yaml

def get_yaml(gfile):
  """ Get configuration yaml for 'item'"""
  f = open(gfile, 'r')
  datadump = yaml.load(f)
  return datadump

def write_yaml(gfile, datadump):
  """ Write configuration yaml for 'item'"""
  f = open(gfile, 'w')
  f.write(yaml.dump(datadump, default_flow_style=False))
  f.close()

CACHE_FILE = '/tmp/rd2etrs.yaml'
coordinates = None

def rd2etrs(xrd, yrd, hnap=0.0):
  """ Convert rd to etrs """
  global coordinates
  if coordinates == None:
    try: 
      coordinates = get_yaml(CACHE_FILE)
      if coordinates.has_key((xrd, yrd)):
       return coordinates[(xrd, yrd)]
    except (IOError,AttributeError):
      coordinates = dict()
      pass

  item = dict()
  item['xrd'] = xrd
  item['yrd'] = yrd
  item['hnap'] = hnap
  f = urllib.urlopen('http://www.rdnap.nl/cgi-bin/rdetrs.pl?func=rd2etrs&xrd=%(xrd)s&yrd=%(yrd)s&hnap=%(hnap)s' % item)
  raw = f.read()
  
  r = re.compile('name="([a-z_]+)" value="([0-9\.]+)"')
  for i in r.finditer(raw):
    name, value = i.group(1,2)
    value = float(value)
    item[name] = value
  
  lam = item['lam_deg'] + (item['lam_min'] + (item['lam_sec'] / 60)) / 60
  phi = item['phi_deg'] + (item['phi_min'] + (item['phi_sec'] / 60)) / 60
  coordinates[(xrd, yrd)] = (phi, lam)
  write_yaml(CACHE_FILE, coordinates)
  return (lam, phi)

OUTFILE = 'network.png'

def make_graph():
  poel = {}
  link_type = {}
  node = {}
  
  nodes = []
  links = []
  try:
    for host in gformat.get_proxylist() + gformat.get_nodelist():
      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('/')

        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])
      lam, phi = rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
      node[host] = (lam, phi)
      nodes += [("POINT(%s, %s)" % (lam, phi))]
  except (KeyError, ValueError), e:
    print "[FOUT] in '%s' interface '%s'" % (host,iface_key) 
    print e
    sys.exit(1)

  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:]:
        links += ["LINESTRING(%s %s,%s %s)" % (node[lid][0], node[lid][1], node[buur][0], node[buur][1])]

  f = open('wktfile.txt', 'w')
  f.write("GEOMETRYCOLLECTION(\n")
  f.write(",\n".join(nodes))
  f.write(",\n".join(links))
  f.write(")\n")
  f.close()


if __name__ == "__main__":
  make_graph()

