#!/usr/bin/perl

use strict vars;
use Env;

# Modify the following two lines to run your kernel from a different location
my $my_kern_path = './kernel/';
my $my_kern_name = 'kernel';

# Modify the following two lines to run the reference kernel from a different
# location, or to run a different reference kernel
my $ref_kern_path = '/afs/cs/academic/class/15441-s06/project3/ref/';
my $ref_kern_name = 'kernel_ref_P2';

# You should not need to modify anything beyond this point.

my $uid = getpwnam($USER);
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 %s -x _15441_gdb_start%d\"&";

my $nodebug_fmt = $stylish_xterm . " -T \"Machine %d\" -e \"%s -f %s -n %d \"&";
my $ref;
my $infile;
my $cmd_fmt = $nodebug_fmt;
my $cfg;

print "Removing any existing temporary files...\n";
system "rm -f core";
system("rm -rf /tmp/__$uid/");
system("rm -f ./_15441_gdb_start*");


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

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

$cfg = shift;

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

foreach (@ARGV) {
    if ($_ eq "debug") {
	$cmd_fmt = $debug_fmt;
    } elsif ($_ eq "ref") {
	$ref = $ref_kern_path.$ref_kern_name;
    }
}

while(<$infile>) {
  if(/^Router\s+(\d+)\s+\{/o) {
    print "\n*** Starting machine $1...\n";
    
    my $kernel = $my_kern_path.$my_kern_name;
    my $status;
    my $cmd;

    # start reference kernel on node 1
    if (defined $ref && $1 eq "1") {
	$kernel = $ref;
    }

    if($cmd_fmt eq $debug_fmt) {
        system("echo \"handle SIGUSR1 pass nostop noprint\nrun -n $1 -f $cfg\" > _15441_gdb_start$1");
        $cmd = sprintf($cmd_fmt, $1, $kernel, $1); 
    } else {
      $cmd = sprintf($cmd_fmt, $1, $kernel, $cfg, $1); 
    }

    print "command: $cmd\n";
    
    $status = system($cmd);

    if($status) {
      print "*** ERROR starting machine $1!\n";
      exit 1;
    }
  }
}

print "\n\n";
