#!/usr/bin/perl 

use work_queue;

my $q = work_queue_create(0);
if (not defined($q)) {
	print "could not instantiate Work Queue master\n";
	exit 1;
}

$port = work_queue_port($q);
print "Listening on port $port.\n"; 

print "Submitting 5 simulation tasks...\n";
for (my $i = 0; $i < 5; $i++) {
	my $infile;
    if ($i == 0){
        $infile = "input.txt";
    } else {
        $infile = sprintf("file.%0.2x", ($i-1));
    }
    my $outfile = sprintf("file.%0.2x", $i);
    my $command = "python simulation.py $i < $infile > $outfile";

    my $t = work_queue_task_create($command);

    work_queue_task_specify_file($t, "simulation.py", "simulation.py", $WORK_QUEUE_INPUT, $WORK_QUEUE_CACHE);
    work_queue_task_specify_file($t, $infile, $infile, $WORK_QUEUE_INPUT, $WORK_QUEUE_CACHE);
    work_queue_task_specify_file($t, $outfile, $outfile, $WORK_QUEUE_OUTPUT, $WORK_QUEUE_NOCACHE);

    my $taskid = work_queue_submit($q, $t);

    print "Waiting for task to complete...\n";
    my $t = work_queue_wait($q, $WORK_QUEUE_WAITFORTASK);

    if (not defined($t)) {
        print "no task returned from wait\n";
    } else {
        if ($t->{return_status} == 0) {
            print "task (id# $t->{taskid}) complete: $t->{command_line} (return code $t->{return_status})\n";
        } else {
            print "task (id# $t->{taskid}) FAILED: $t->{command_line} (return code $t->{return_status}); output: $t->{output}\n";
        }
        work_queue_task_delete($t);
    }
}

print "done.\n";

work_queue_delete($q);

exit 0;
