#!/usr/bin/perl

use strict vars;
use Env;

my $uid = 0;
my $gdb = "/afs/andrew/course/15/441-2/gdb/bin/gdb";
my $debug_fmt = "xterm -sl 1000 -T \"Routing daemon %d\" -e $gdb srouted &";
my $nodebug_fmt = "xterm -sl 1000 -T \"Routing daemon %d\" -e ./srouted -n %d -node %d -f %s &";
my $vg_fmt = "xterm -sl 1000 -T \"Routed %d\" -e doit valgrind ./srouted  -n %d  -node %d -f %s&";
my $cmd_fmt;
my $cmd;

my $infile = 0;
my $status = 0;

# ======================================================================
# Main Procedure
# ======================================================================

if($#ARGV < 0) {
        print stderr "\nusage: $0 <configuration file> [debug]\n\n";
        exit 1;
}

if(! open $infile, $ARGV[0]) {
        print stderr "Could not open $ARGV[0]\n";
        exit 1;
}

if($#ARGV == 1 && $ARGV[1] eq "debug") {
  $cmd_fmt = $debug_fmt;
} elsif ($ARGV[1] eq 'vg') {
	$cmd_fmt = $vg_fmt;
} else {
  $cmd_fmt = $nodebug_fmt;
}

$uid = getpwnam($USER);
print STDERR "Removing any existing temporary files...\n";
system "rm -f core";
#system("rm -f /tmp/__$uid/__link_*");
#system("rm -f /tmp/__$uid/__kern_*");
#system("rm -f /tmp/__$uid/__user_*");
#system("rm -f /tmp/__$uid/__snmp_*");

while(<$infile>) {
  if(/^Router\s+(\d+)\s+\{/o) {
    #print "\n*** Starting machine $1...\n";
    
    if($cmd_fmt eq $debug_fmt) {
      $cmd = sprintf($cmd_fmt, $1); 
    } else {
      $cmd = sprintf($cmd_fmt, $1, $1, $1, $ARGV[0]); 
    }
    
#print "command: $cmd\n";
    
    $status = system($cmd);
    if($status) {
      print "*** ERROR starting machine $1!\n";
      exit 1;
    }
  }
}
print "\n\n";
