#!/usr/bin/perl
#
# $Id: genconfig.pl,v 1.1 2002/11/16 09:42:07 jclopez Exp $
#
# Config files generation
# Language: Perl
#
# Copyright (C) 2002	Julio Lopez	All Rights Reserved.
# See disclaim.txt for disclaimer and copyright information.
#
# Arguments:
# - network-file
# - group-number
# - host-file [optional]


#
# are there the right number of arguments?
#
if (@ARGV < 2 or @ARGV > 3) {
  print "usage: ", $0, " <network-file> <group-number>\n";
  print <<EOF;

  Parameters:
    network-file:  The name of the file that describes the network.
                   See explanation below.
    group-number:  your group number.

  The network file contains the topology of the network in
  an adjacency list.
  Each line in the file describes a link between node n1 and n2.
  A line contains the node ids for the two end points of the link.
  E.g.,

   2 4
   3 2
   5 6
   ...

  The script generates a set of configuration files for the nodes
  in the network.  The names of the output files are of the form:
  node<nodeid>.conf

EOF
  exit(0);
}

$netfile = $ARGV[0];
$group   = $ARGV[1];

#
# open the input message file
#
open(NETFILE, $netfile)
  or die("error: couldn't open " . $netfile . "\n");

$node_count = 0;
$link_count = 0;
@nodes = ();
$line = 0;

while (<NETFILE>) {
  ($n1, $n2) = split;		#(' ', $_);
  $line++;

  if ($n1 == 0 || $n2 == 0) {
    if (!chomp) {
      print "WARNING: Found and invalid entry in line $line: $_\n";
    }
  } else {
#    print "Node 1: $n1, Node 2: $n2\n";

#    if (!defined($nodes[$n1])) {
#      $nodes[$n1] = [ $n2 ];
#    } else {
#      push(@{$nodes[$n1]}, $n2);
#    }

#    if (!defined($nodes[$n2])) {
#      $nodes[$n2] = [ $n1 ];
#    } else {
#      push(@{$nodes[$n2]}, $n1);
#    }

    $link_count++;
    push(@{$nodes[$n1]}, $n2);
    push(@{$nodes[$n2]}, $n1);
  }
}

$baseport = 20000 + 100*$group;

for ($i = 1; $i <= $#nodes; $i++) {
  if (defined $nodes[$i]) {

    unless (open(NODEFILE, ">node$i.conf")) {
      print "Error opening config file for node $i\n";
      next;
    }

    $route_port = $baseport + ($i - 1)*2;
    $fwd_port   = $route_port + 1;

    print NODEFILE "$i localhost $route_port $fwd_port\n";

    foreach $entry (@{$nodes[$i]}) {
      $route_port = $baseport + ($entry - 1)*2;
      $fwd_port   = $route_port + 1;

      print NODEFILE "$entry localhost $route_port $fwd_port\n";
    }

    close(NODEFILE);

    $node_count++;
  }
}


if (open(SUMFILE, ">net.txt")) {
  $date = `date`;
  print SUMFILE "Net configuration summary file\n";
  print SUMFILE "Date:\t\t\t$date";
  print SUMFILE "Net file:\t\t$netfile\n";
  print SUMFILE "Group number:\t\t$group\n";
  print SUMFILE "Number of nodes:\t$node_count\n";
  print SUMFILE "Number of links:\t$link_count\n";
}
