#!/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():
  f = open('kmlfile.kml', 'w')
  f.write("""
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.0">
  <Document>
    <name>KML Samples</name>
    <open>1</open>
    <description>Unleash your creativity with the help of these examples!</description>
    <Style id="downArrowIcon">
      <IconStyle>
        <Icon>
          <href>http://maps.google.com/mapfiles/kml/pal4/icon28.png</href>
        </Icon>
      </IconStyle>
    </Style>
    <Style id="globeIcon">
      <IconStyle>
        <Icon>
          <href>http://maps.google.com/mapfiles/kml/pal3/icon19.png</href>
        </Icon>
      </IconStyle>
      <LineStyle>
        <width>2</width>
      </LineStyle>
    </Style>
    <Style id="transPurpleLineGreenPoly">
      <LineStyle>
        <color>7fff00ff</color>
        <width>4</width>
      </LineStyle>
      <PolyStyle>
        <color>7f00ff00</color>
      </PolyStyle>
    </Style>
    <Style id="yellowLineGreenPoly">
      <LineStyle>
        <color>7f00ffff</color>
        <width>4</width>
      </LineStyle>
      <PolyStyle>
        <color>7f00ff00</color>
      </PolyStyle>
    </Style>
    <Style id="thickBlackLine">
      <LineStyle>
        <color>87000000</color>
        <width>10</width>
      </LineStyle>
    </Style>
    <Style id="redLineBluePoly">
      <LineStyle>
        <color>ff0000ff</color>
      </LineStyle>
      <PolyStyle>
        <color>ffff0000</color>
      </PolyStyle>
    </Style>
    <Style id="blueLineRedPoly">
      <LineStyle>
        <color>ffff0000</color>
      </LineStyle>
      <PolyStyle>
        <color>ff0000ff</color>
      </PolyStyle>
    </Style>
    <Style id="transRedPoly">
      <LineStyle>
        <width>1.5</width>
      </LineStyle>
      <PolyStyle>
        <color>7d0000ff</color>
      </PolyStyle>
    </Style>
    <Style id="transBluePoly">
      <LineStyle>
        <width>1.5</width>
      </LineStyle>
      <PolyStyle>
        <color>7dff0000</color>
      </PolyStyle>
    </Style>
    <Style id="transGreenPoly">
      <LineStyle>
        <width>1.5</width>
      </LineStyle>
      <PolyStyle>
        <color>7d00ff00</color>
      </PolyStyle>
    </Style>
    <Style id="transYellowPoly">
      <LineStyle>
        <width>1.5</width>
      </LineStyle>
      <PolyStyle>
        <color>7d00ffff</color>
      </PolyStyle>
    </Style>
    <Style id="noDrivingDirections">
      <BalloonStyle>
        <text><![CDATA[
          <b>$[name]</b>
          <br /><br />
          $[description]
        ]]></text>
      </BalloonStyle>
    </Style>
    <Folder>
      <name>Paths</name>
      <visibility>0</visibility>
      <description>Examples of paths. Note that the tessellate tag is by default
        set to 0. If you want to create tessellated lines, they must be authored
        (or edited) directly in KML.</description>
    """)

  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)
      f.write("""
		<Placemark>
			<name>Blue Icon</name>
			<description>Just another blue icon.</description>
			<styleUrl>./styles.kml#blueIcons</styleUrl>
			<Point>
				<coordinates>%s,%s,630</coordinates>
			</Point>
		</Placemark>
   """ % (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:]:
        f.write("""
      <Placemark>
        <name>Untessellated</name>
        <visibility>0</visibility>
        <description><![CDATA[If the <tessellate> tag has a value of 0, the line follow a simple straight-line path from point to point]]></description>
        <LineString>
          <tessellate>0</tessellate>
          <coordinates> %s, %s, 0
            %s , %s, 0 </coordinates>
        </LineString>
      </Placemark>
      """ % (node[lid][0], node[lid][1], node[buur][0], node[buur][1]))
  f.write("""
    </Folder>
  </Document>
</kml>
  """)
  f.close()


if __name__ == "__main__":
  make_graph()

