<?php
function hexdump($string) {
	$out = array();
	for($i = 0; $i < strlen($string); $i++) {
		$out[] = ord($string[$i]);
	}
	return implode(" ", $out);
}

function run($dirname, $classname, $testno, $link) {
	$out = array("interror" => 0, "retval" => 0, "stdout" => "", "stderr" => "");
	$testno = intval($testno);

	echo "<B>Running test $testno</B><BR>\n";

	$query = "SELECT policy, input, inputfile, output, outputfile FROM tests WHERE testno = $testno";
	$result = mysql_query($query, $link) or die("Can't fetch test data: ".mysql_error($link));
	if(mysql_num_rows($result) != 1) {
		$out["interror"] = 2;
		$out["stderr"] = "Not one set of test data";
		return $out;
	}
	$line = mysql_fetch_array($result);
	$policyfile = $dirname."/policy.txt";
	$inputfile = $dirname."/input.txt";
	$outputfile = $dirname."/out".mt_rand().".txt";

	$out = put_file($policyfile, $line["policy"]);
	if($out["interror"] != 0) {
		return $out;
	}

	if($line["inputfile"] != "" ) {
		$out = put_file($inputfile, $line["inputfile"]);
		if($out["interror"] != 0) {
			return $out;
		}
	}

	$fd_conf = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
	$cmd = getcwd()."/limiter java -Djava.security.manager -Djava.security.policy==$policyfile $classname";
	if($line["inputfile"] != "") {
		$cmd .= " $inputfile";
	}
	if($line["outputfile"] != "") {
		$cmd .= " $outputfile";
	}
	$pp = proc_open("$cmd", $fd_conf, $fd, "$dirname");
	if(!$pp) {
		$out["interror"] = 3;
		$out["stderr"] = "Can't start java program";
		return $out;
	}
	fwrite($fd[0], $line["input"]);
	fflush($fd[0]);

	$out["stdout"] = stream_get_contents($fd[1]);
	$out["stderr"] = stream_get_contents($fd[2]);

	if($line["output"] != "") {
		$match = preg_match($line["output"], $out["stdout"]);
		if($match == false) {
			$out["retval"] = 1;
			$out["stderr"] = "Output &quot;{$out["stdout"]}&quot; does not match specification";
			//$out["stderr"] = "Output <BR>".hexdump($out["stdout"])." does not match <BR>".hexdump($line["output"]);
			return $out;
		}
	}

	if($line["outputfile"] != "") {
		if(file_get_contents($outputfile) != $line["outputfile"]) {
			$out["retval"] = 1;
			$out["stderr"] = "Output file does not match specification";
			//$out["stderr"] = "Outputfile <BR>".hexdump(file_get_contents($outputfile))." does not match <BR>".hexdump($line["outputfile"]);
			return $out;
		}
	}

	$ret = proc_close($pp);
	$out["retval"] = $ret;

	return $out;
}

function run_test($dirname, $classname, $testno, $sid, $link) {
	include_once("test_helper.php");

	$run_ret = run($dirname, $classname, $testno, $link);
	save_test($run_ret, $testno, $sid, $link);

	/*
	while(list($key, $val) = each($run_ret)) {
		echo "$key =&gt; $val <BR>\n";
	}
	*/

	return $run_ret;
}
?>
