#!/usr/bin/perl

use strict vars;
use Env;

my $uid = 0;
my $gdb = "gdb";
my $stylish_xterm = "xterm -geom 80x25 -fg white -bg black -sl 1000 ";

my $debug_fmt = $stylish_xterm . " -T \"Machine %d\" -e \"$gdb ./kernel/kernel -x _15441_gdb_start%d\"&";

my $nodebug_fmt = $stylish_xterm . " -T \"Machine %d\" -e \"./kernel/kernel -f %s -n %d \"&";

my $vg_fmt = "xterm -sl 1000 -T \"Machine %d\" -e doit valgrind ./kernel/kernel -f %s -n %d &";

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 "Removing any existing temporary files...\n";
system "rm -f core";
system("rm -rf /tmp/__$uid/");
system("rm -f ./_15441_gdb_start*");

sleep(2);

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

print "\n\n";
