#!/usr/bin/perl

use warnings;
use strict;

my $graph;

my ($max,$min);

foreach my $file ( glob '*/*.np' ) {

	my $direction = $file;
	$direction =~ s/\.np$//;
	my ( $from, $to ) = split(m{/},$direction,2);

	my $line = `tail -1 $file`;
	$line =~ s{^\s+}{};
	$line =~ s{\s+$}{};
	my ( $size, $speed, $rtt ) = split(/\s+/, $line);

	warn "$from -> $to | $size | $speed | $rtt\n";

	my $len = int($speed / 100);

	my $rev = qq|"$to" -> "$from"|;

	# make edge bi-directional if speed difference is less then 10%
	if ( $graph->{$rev} && abs($graph->{$rev}->{speed}->[0] - $speed) < ($speed/10) ) {
		$graph->{$rev}->{speed}->[1] = int($speed);
		$graph->{$rev}->{dir} = 'both';
	} else {
		$graph->{ qq|"$from" -> "$to"| } = {
			size => $size,
			speed => [ int($speed) ],
			rtt => $rtt,
			dir => 'forward',
		};
	}

	$min ||= $speed;
	$min = $speed if $speed < $min;

	$max ||= $speed;
	$max = $speed if $speed > $max;

}

warn "# speed $min ... $max\n";

print qq|
digraph "netpipe" {
|,
join("\n", map {
	my $node = $_;
	my @speed = @{ $graph->{$node}->{speed} };
	my $speed = 0;
	$speed += $_ foreach @speed;
	$speed /= $#speed + 1;
	my $c = 'ff0000';
	$c = '00ff00' if ( $speed /  100 ) > 5;
	$c = '0000ff' if ( $speed / 1000 ) > 1;
	$c = '8888ff' if ( $speed / 1000 ) > 2;
	my $label = qq|labelfontsize=10,weight=$speed,|;
	$label .= qq|headlabel=$speed[0],| if $speed[0];
	$label .= qq|taillabel=$speed[1],| if $speed[1];
	$label .= qq|style=dashed,| if $graph->{$node}->{dir} eq 'both';
	qq|$node [ $label color="#$c",dir=$graph->{$node}->{dir} ]|;
} keys %$graph),
qq|
}
|;

