#!/usr/bin/perl -w

use Getopt::Std;
getopts("m:c:n:h:z");

if ($opt_m) {
    $MACHINES = $opt_m;
} else {
    $MACHINES= 2;
}

if ($opt_c) {
    $CPUS = $opt_c;
} else {
    $CPUS = 2;
}

if ($opt_n) {
    $SIMNAME = "$opt_n";
} else {
    die "Please give the simulation name!\n";
}

if ($opt_h) {
    @nl = split /\D/, $opt_h;
    for $i (@nl) {
	push @H, "ferrari00$i";
    }

} else {
    push @H, 
    "ferrari001",
    "ferrari002", 
    "ferrari003",
    "ferrari004",
    "ferrari005",
    "ferrari006",
    "ferrari007",
    "ferrari008";
}

if ($opt_z) {
    if ($#H + 2 < $MACHINES) {
	die "Hosts (@H) plus 1 less than no. of machines needed $MACHINES in the special case!\n";
    }
} else {
    if ($#H + 1 < $MACHINES) {
	die "Hosts (@H) less than no. of machines $MACHINES needed!\n";
    }
}

$SS = int(rand(20000))+10000; #random number as a session name
$SS = "session-$SS";
$MP = int(rand(2000))+23456; #random number as a master port
$SHMKEY = int(rand(50000)); #rand number as a shared memory key

$TP=`pwd`;
chomp $TP;

$node_number = $MACHINES * $CPUS;
for $i (0..$MACHINES-1) {
    for $j (0..$CPUS-1) {
	if ($opt_z) {
	    if ($i==0 and $j==0) {
		push @NODES, $H[$i];
	    } else {
		push @NODES, $H[$i+1];
	    }
	} else {
	    push @NODES, $H[$i];
	}
    }
}

$nodes_str = join(",", @NODES);
$node_cnt = 0;

print "SS=$SS, MP=$MP\n";
for $i (0..$MACHINES-1) {

    for $j (0..$CPUS-1) {
	
	$rshcmd = "export NODEINFO=$node_number:$nodes_str:$node_cnt; " .
	    "export SESSIONNAME=$SS; " . 
#	    "export FMTCP_MASTERPORT=$MP; " . 
	    "export FMSHM_KEY=$SHMKEY; " .
	    "export FMSHM_DEBUG=1; " .
	    "export FMSHM_BUFSPERPEQ=1000; " .
	    "cd $TP;" .
	    "/usr/bin/time pdns $SIMNAME\_$i\_$j.tcl >| $SIMNAME\_$i\_$j.log";
	$cmd = "rsh $NODES[$node_cnt] '$rshcmd' &";
	print "$cmd\n";
	system $cmd;
	$node_cnt ++;
    }
}
