# Usage:
#
# $ find . -name wleiden.conf > l
#
# prune demo, test and uninteresting stuff from l
#
# $ python channelplot.py
# $ gv channelplot.ps
#
# needs graphviz (http://www.graphviz.org/) to run
import os
import re
import string

ipdict = {}
ipnr_node = {}
node_ipnr = {}
node_wi_channel = {}
node_links = {}
node_links_channel = {}
nodelabel = {}

def parse_wleiden_conf(lines):
	ipnr = None
	wi = None
	peer = None
	omni = 0
	for l in lines:
		if wi != None:
			match = re.match("^\EW.*", l)
			if match != None:
				wi = None
				ipnr = None
				peer = None
				continue
			match = re.match("^SDESC=omni.*", l)
			if match != None:
				omni = 1
			match = re.match("^IP=([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*).*", l)
			if match != None:
				ipnr = match.group(1)
				if not node_ipnr.has_key(nodename):
					node_ipnr[nodename] = []
				node_ipnr[nodename].append(ipnr)
				ipnr_node[ipnr] = nodename
			match = re.match("^POINT_TO_POINT=([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*).*", l)
			if match != None:
				peer = match.group(1)
				if not node_links.has_key(nodename):
					node_links[nodename] = []
				node_links[nodename].append( (peer, wi) )
			match = re.match("^CHANNEL=([0-9]*).*", l)
			if match != None:
				if omni == 1:
					nodelabel[nodename] = "%s\\n(%s)" % (nodename, match.group(1) )
				else:
					node_wi_channel[(nodename, wi)] = match.group(1)
		else:
			match = re.match("^\$nodename='([^']*)';.*", l)
			if match != None:
				nodename = match.group(1).lower()
			match = re.match("^\$config{'(wi[0-9]*).*", l)
			if match != None:
				wi = match.group(1)
				omni = 0

for fname in open("l").readlines():
	parse_wleiden_conf(open(fname[:-1]).readlines())

out = open("foo.dot", "w")
out.write("digraph channelplot {\n")
for node in node_ipnr.keys():
	if nodelabel.has_key(node):
		label = "[label=\"%s\"]" % nodelabel[node]
	else:
		label = ''
	out.write("\t%s %s\n" % (node, label))
for node in node_ipnr.keys():
	if node_links.has_key(node):
		for peer, wi in node_links[node]:
			if ipnr_node.has_key(peer):
				if node_wi_channel.has_key( (node,wi) ):
					label = "[label=\"%s\"]" % node_wi_channel[ (node, wi) ]
				else:
					label = ''
				out.write("%s -> %s%s\n" % (node, ipnr_node[peer], label))
			else:
				# link naar onbekend iemand, zal wel niet
				# belangrijk zijn.
				pass
out.write("}\n")
out.close()
os.system('neato -Gstart=foo -Goverlap=false/scale -Gsplines=true -Gsep=2 -Gratio=fill -Gnslimit=50.0 -Grotate=90 -Gsize="11,7.5" -Tps -o channelplot.ps foo.dot')

