#! /usr/bin/perl

use strict;

my $platfile = $ARGV[0] || die "Usage: $0 platfile daxfile\n";
my $daxfile = $ARGV[1] || die "Usage: $0 platfile daxfile\n";

sub title {
    my $l = "XXXX $0: $_[0] XXXX";
    my $l2 = $l;
    $l2 =~ s/./X/g;
    print STDERR "\n\n$l2\n$l\n$l2\n";
}

title("relaunching make");
system qw(make -C ../../../src libsimgrid.la) and die "XXXX $0: make library failed: $?\n";  
system qw(make -C ../../simdag dax/dax_test) and die "XXXX $0: make dax_test failed.\n";
system qw(make replay_simulator) and die "XXXX $0: make replay_simulator failed.\n";

###################################################
my $tracefile = "$daxfile";
$tracefile =~ s/\.xml$//;
$tracefile .= ".trace";
title("Regenerating the trace '$tracefile'");
my @args = ("../../simdag/dax/dax_test", "$platfile", "$daxfile","$tracefile");
system @args and die "XXXX $0: cannot regenerate the trace '$tracefile': $?\n";


###################################################
my $deployfile = "deploy_$platfile";
$deployfile =~ s/\.xml$//;
$deployfile .= "_".$daxfile;
title("Generate a deployment file '$deployfile'");
my %hosts;

print STDERR  "$0: parsing the trace file '$tracefile'\n";
open TRACE,"$tracefile" || die "$0: cannot open tracefile $tracefile: $!\n";
while (<TRACE>) {
    #    print "Seen $_";
    next unless /compute/;
    m/^\[.*?\] ([^ ]*) .*$/ || die "unparsable line: $_";
    if (defined $hosts{$1}) {
	$hosts{$1}+=1;
    } else {
	$hosts{$1}++;
    }
} 
close TRACE;
my @hostnames = sort keys %hosts;
my $master = $hostnames[0];

foreach my $host (@hostnames) {
    if ($host ne $master && $hosts{$host} > 1) {
	print STDERR "$host computes $hosts{$host} times!\n";
    }
}

print STDERR  "$0: Generating the xml deployment file\n";
open DEPLOY,">$deployfile";
print DEPLOY "<?xml version='1.0'?>\n";
print DEPLOY "<!DOCTYPE platform SYSTEM \"simgrid.dtd\">\n\n";
print DEPLOY "<!-- File generated by \"$0 $tracefile\" at ".(localtime())." -->\n\n";
print DEPLOY "<platform version=\"2\">\n";

print DEPLOY "  <process host=\"$master\" function=\"master\">\n";
print DEPLOY "    <argument value=\"$tracefile\" /> <!-- trace file -->\n";
print DEPLOY "    <argument value=\"4500\"/>            <!-- port number -->\n";
print DEPLOY "  </process>\n";

foreach my $host (@hostnames) {
    print DEPLOY "  <process host=\"$host\" function=\"worker\">";
    print DEPLOY "<argument value=\"$master:4500\" />";
    print DEPLOY "</process>\n";
}

print DEPLOY "</platform>\n";
close DEPLOY;
print STDERR  "$0: Xml deployment file generated\n";

###################################################
title("Replay this trace onto the simulator");
system ("./replay_simulator","$platfile","$deployfile")
  and die "Cannot replay the trace. Command was:\n./replay_simulator $platfile $deployfile\n";


# 