#!/bin/csh -f
#!/usr/bin/perl -w
eval 'exec perl -x -w -S $0 $*:q'
 if 0;

$optVerbose = 0;
$benchmark = "";
$benchFile = "";
$simFile = "";
$benchArgs = "";
$configFile = "";
$simulator = "sim_smt";
$ignore = 1;  # Ignore args beginning with "-" until we see the benchmark name
while (@ARGV) {
    $_ = shift(@ARGV);
    
    # Check for - or -- options first
    if (/^-v$/) {
	$optVerbose=1;
    }
    elsif (/^-config/) {
	$configFile = shift @ARGV;
    }
    elsif (/^-sim/) {
	$simulator = shift @ARGV;
    }
    elsif (/^-redir:sim/) {
	$simFile = shift @ARGV;
    }
    elsif (/^-redir:prog/) {
	$benchFile = shift @ARGV;
    }
    elsif (/^(-.*)/) {
        if ($ignore) {
	    print STDERR "Ignoring simulator option $1\n";
	}
	else {
	    $benchArgs .= "$1 ";
	}
    }
    elsif (/^(.*)/) {
	if ($benchmark eq "") {
	    $benchmark = $1;
	    $ignore = 0;
	}
	else {
	    if ($optVerbose) {
		print STDERR "Passing program arg $1\n";
	    }
	    $benchArgs .= "$1 ";
	}
    }
}

open(CFG, "< $configFile") || die "Can't open config file $configFile\n";
while (<CFG>) {
    if (/cpu:(\S*)/) {
	$cpu = $1;
	last;
    }
}
close CFG;

open(INI, "> benchmark.ini") || die "Can't open benchmark.ini\n";
print INI "[ss-benchmark]\n";
print INI "type=LiveProcess\n";
print INI "cmd=$benchmark $benchArgs\n";
print INI "env=";
foreach $key (keys %ENV) {
    if ($ENV{$key} ne "") {
	print INI "$key $ENV{$key} ";
    }
}
print INI "\n";
if ($benchFile ne "") {
    print INI "output=$benchFile\n";
}
print INI "\n";
print INI "[$cpu]\n";
print INI "workload=ss-benchmark:ss-benchmark\n";

close INI;

if ($optVerbose) {
    print STDERR "Running $simulator $configFile\n";
}

$filedesc = fileno(STDIN);
print STDERR "ss standard input from file descriptor $filedesc\n";
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
    = stat STDIN;
print STDERR "ss standard input $dev-$ino has mode $mode\n";
1 || die "This is here to prevent typo warnings $nlink $uid $gid $rdev $size $atime $mtime $ctime $blksize $blocks";

$rc = system("$simulator $configFile");
if ($optVerbose) {
    print STDERR "Got return value $rc\n";
}

exit $rc/256;
