<?
//dl ("../../../../../apps/ssh2-0.10/modules/ssh2.so");

require "mysqlconnect.inc.php";
 

/******* send a data file and a command file on the remote machine*********/
function fnSendAllData($application, $data, $command){
        if(func_num_args()>=1){  // if there is at least one argument

		//get the ssh connection to dedicated machine
		$machineid = getConnection(array('appname' => $application, 'state' => 2));
		//create the temporary location on the remote machine
		$pathId = substr(uniqid("5555"),-5);
		
		$cmd = "mkdir $pathId";
		$stream=ssh2_exec($GLOBALS['ssh2connection'],$cmd);
		stream_set_blocking($stream,true);
		$res=fread($stream,4096);
		fclose($stream);

		$cmd = "chmod 777 $pathId";
		$stream=ssh2_exec($GLOBALS['ssh2connection'],$cmd);
                stream_set_blocking($stream,true);
                $res=fread($stream,4096);
                fclose($stream);

		$uploaddir = $GLOBALS['uploaddir'];
		$sendfile = $uploaddir.$_FILES['uploadDFile']['name'];

		if (!ssh2_scp_send($GLOBALS['ssh2connection'],"$sendfile","./$pathId/data.txt",0755))
        		die("unable to scp send");


		$sendfile = $uploaddir.$_FILES['uploadCFile']['name'];
		
		if (!ssh2_scp_send($GLOBALS['ssh2connection'],"$sendfile","./$pathId/commands.txt",0755))
        		die("unable to scp send");

		$machinetable = $GLOBALS['machinetable'];
		$jobtable = $GLOBALS['jobtable'];
		$commandtable = $GLOBALS['commandtable'];
		$date = date("D M j G:i:s T Y");

		//extract the command to be run from the command table
		$query = "SELECT * from $commandtable where softname='$application'";
		$result = mysql_fetch_assoc(mysql_query($query));
		$command = parseComDB($result['command'], $result['input_file'], $result['output_file'], $result['parameters']);
		//print($command."<br>");
 		$dd = getMch($application);	
		//print($dd[0]."Hello <BR>");
		$query="INSERT INTO $jobtable SET appname='$application', dlocation='$pathId', clocation='$pathId', command='$command', submitdate='$date', alivetime='0:0:0', state=1, remote_machines_id=$dd[0]";
		$result = mysql_query($query);

		//prepare the job to be run on the remote machine
		$query = "SELECT dlocation FROM $jobtable WHERE submitdate='$date'";
		$temp  = mysql_fetch_row(mysql_query($query));
	        $temp = $temp[0];
		$GLOBALS['rkey'] = $temp;

	
		$cmd = "/usr/local/bin/screen -D -m ./prec/ssh2.compute.pl '$date' \n";
		$shell = ssh2_shell($GLOBALS['ssh2connection'], 'xterm', null, 80, 24, SSH2_TERM_UNIT_CHARS);
		fwrite($shell,$cmd);
		sleep(1);
		
		// Then u can fetch the stream to see what happens on stdio
		while($line = fgets($shell)) {
			flush();
			echo $line."<br />";
 		}

                fclose($shell);


        } else {die('No arguments passed');}  // stops if nothing is
}

/******* send a command file on the remote machine*********/
function fnSendComData($application, $command){
        if(func_num_args()>=1){  // if there is at least one argument

                //get the ssh connection to dedicated machine
                $machineid = getConnection(array('appname' => $application, 'state' => 2));
                //create the temporary location on the remote machine
                $pathId = substr(uniqid("5555"),-5);

                $cmd = "mkdir $pathId";
                $stream=ssh2_exec($GLOBALS['ssh2connection'],$cmd);
                stream_set_blocking($stream,true);
                $res=fread($stream,4096);
                fclose($stream);

                $cmd = "chmod 777 $pathId";
                $stream=ssh2_exec($GLOBALS['ssh2connection'],$cmd);
                stream_set_blocking($stream,true);
                $res=fread($stream,4096);
                fclose($stream);

		$uploaddir = $GLOBALS['uploaddir'];
                $sendfile = $uploaddir.$_FILES['uploadCFile']['name'];

                if (!ssh2_scp_send($GLOBALS['ssh2connection'],"$sendfile","./$pathId/commands.txt",0755))
                        die("unable to scp send");

                $machineip = $GLOBALS['ssh2host'];
                $machinetable = $GLOBALS['machinetable'];
                $jobtable = $GLOBALS['jobtable'];
                $date = date("H:i:s");
                $query = "SELECT id from $machinetable WHERE iplocation = '$machineip'";
                $result = mysql_fetch_assoc(mysql_query($query));
                $result = $result['id'];
                $command = $GLOBALS['appstrings']['R']."./commands.txt >& ./results";

                $query="INSERT INTO $jobtable SET appname='$application', dlocation='$pathId', clocation='$pathId', command='$command', submitdate='$date', alivetime='0:0:0', state=1, remote_machines_id=$result";
                $result = mysql_query($query);

                //prepare the job to be run on the remote machine
                $query = "SELECT dlocation FROM $jobtable WHERE submitdate='$date'";
                $temp  = mysql_fetch_row(mysql_query($query));
                $temp = $temp[0];
		$GLOBALS['rkey'] = $temp;


                $cmd = "/usr/local/bin/screen -d -m ./prec/ssh2.compute.pl $date \n";

                $shell = ssh2_shell($GLOBALS['ssh2connection'], 'xterm', null, 80, 24, SSH2_TERM_UNIT_CHARS);
                fwrite($shell,$cmd);
                //$shell=ssh2_exec($GLOBALS['ssh2connection'], 'bash', 'xterm');
                //fclose($shell);
                //$shell=ssh2_exec($GLOBALS['ssh2connection'], $cmd, 'xterm');
                //stream_set_blocking($shell,true);
                sleep(1);

                // Then u can fetch the stream to see what happens on stdio
                while($line = fgets($shell)) {
                        flush();
                        //echo $line."<br />";
                }

//                fclose($shell);

        } else {die('No arguments passed');}  // stops if nothing is
}


/******* Initialize given machine ********/
function initMch($ip){
	$conn = retConnection($ip);
	if (!ssh2_scp_send($conn,"prec.tar.gz","./prec.tar.gz",0755))
		die("unable to scp send");
	$cmd = "tar zxvf prec.tar.gz \n";	
	$shell = ssh2_shell($GLOBALS['ssh2connection'], 'xterm', null, 80, 24, SSH2_TERM_UNIT_CHARS);
                fwrite($shell,$cmd);

	


}
/******* Return a single machine Id based on desired application and minimum load ********/
function getMch($application){
	$table = $GLOBALS['machinetable'];
	$query = "SELECT id, MIN(state) from $table WHERE availsoft like '%$application%'  GROUP BY id";
	$temp  = mysql_query($query);
	return mysql_fetch_row($temp);
}
/******* Generate a valid command from the remote_command table fields ********/
function parseComDB($application, $input, $output, $parameters){

	$command = $parameters;
	$command = substr_replace($command, $output, strpos($command, "O"), 1);
	$command = substr_replace($command, $input, strpos($command, "I"), 1);
	$command = substr_replace($command, $application, strpos($command, "C"), 1);
	return $command;

}

/******* Modify the path to the data file - set it to temp directory*********/
function parseComFile($file, $path){
	$fc = file($file);
	$pat = '/read\Wtable\W{n}/i';
	$pattern = '/(\w+)<-(\w+)\W\"[:print:]\"*/i';
	$replace = '/(\w+)<-(\w+)\W\"[:print:]\"*/i';
	foreach($fc as $line){
		print($line."<br>");
		preg_match($pat, $line, $matches, PREG_OFFSET_CAPTURE, 3);
		print_r($matches);
	}
}

/******* Clean a given process from DB and from the HDD ********/

function fnCleanSingle($id){
	$jobtable = $GLOBALS['jobtable'];
	$query = "SELECT dlocation FROM $dbtable WHERE id='$id'";
	$pathId = mysql_fetch_assoc(mysql_query($query));
	
	$cmd = "rm -rf $pathId";
        $stream=ssh2_exec($GLOBALS['ssh2connection'],$cmd);
        stream_set_blocking($stream,true);
        $res=fread($stream,4096);
        fclose($stream);

	$query = "DELETE FROM $dbtable WHERE id='$id'";
	$result = mysql_query($query);
}

/******* Clean a given process from DB and from the HDD ********/
function fnCleanAll(){
	$jobtable = $GLOBALS['jobtable'];
	$query = "SELECT id FROM $dbtable";
	$id = mysql_fetch_array(mysql_query($query), MYSQL_NUM);
	for ($r = 0; $r < count($id); $r++){
		fnCleanSingle($id);
	}
}

/******* get the results from the remote machine and send it back to the interface *********/
function fnGetResults($id){
	if ($argc < 1) die('No arguments passed');  // stops if nothing is
	$query = "SELECT $dlocation FROM $dbtale WHERE 'id'=$id";
	$result = mysql_query($query);

	if (!ssh2_scp_recv($connection,"$result/result","$result/result"))
        	die("unable to scp receive");
	else
        	print "file received successfully through scp\n";
}
  
/******* check if the table exists *********/
function fnTableExists($TableName) {
	$database = $GLOBALS['database'];

	//Verifies that a MySQL table exists
	$bRetVal = FALSE;
	$query = "SHOW TABLES FROM $database";
	$result = mysql_query($query);

	while ($row=mysql_fetch_array($result)) {
		if ($row[0] ==  $TableName)
			$bRetVal = TRUE;
	}
	mysql_free_result($result);
	return ($bRetVal);
}


/******* check if the database exists *********/
function fnDatabaseExists($dbName) {
	$dbconnection = $GLOBALS['dbconnection'];

	//Verifies existence of a MySQL database
	$bRetVal = FALSE;
	$result = mysql_list_dbs($dbconnection);
	while ($row=mysql_fetch_array($result, MYSQL_NUM)) {
		if ($row[0] ==  $dbName)
			$bRetVal = TRUE;
	}
	mysql_free_result($result);
	return ($bRetVal);
}
  
/******* establish a connection according to some criteria *******/
function getConnection($parameters){
	$app = $parameters['appname'];
	$state = $parameters['state'];
	$machinetable = $GLOBALS['machinetable'];

	$query = "SELECT * from $machinetable WHERE state <= '$state' AND availsoft like '%$app%'";
	if (!($result = mysql_query($query)))
		print("Result from connection: ".$query);
	if ($assoc = mysql_fetch_assoc($result)){
		$id = $assoc['id'];
		$query = "SELECT iplocation from $machinetable WHERE id = $id";
		$res = mysql_fetch_assoc(mysql_query($query));
		getssh2Connection($res['iplocation']);
		return $id;	
	}
}
/******** connect to a particular machine *******/
function getssh2Connection($machine){

	if (isset($GLOBALS['ssh2connection']))
		unset($GLOBALS['ssh2connection']);
	$GLOBALS['ssh2connection'] = ssh2_connect($machine,"22");
	if (!$GLOBALS['ssh2connection']) {
        	die("unable to connect");
	}

	// authorize
	if (!ssh2_auth_password($GLOBALS['ssh2connection'],$GLOBALS['ssh2user'],$GLOBALS['ssh2passwd'])) {
	        die("unable to authorize");
	}
	$GLOBALS['ssh2host'] = $machine;
}
/******* establish a connection for the given IP *******/
function retConnection($ip){

	if (isset($GLOBALS['ssh2connection']))
		unset($GLOBALS['ssh2connection']);
	$GLOBALS['ssh2connection'] = ssh2_connect($ip,"22");
	if (!$GLOBALS['ssh2connection']) {
        	die("unable to connect");
	}

	// authorize
	if (!ssh2_auth_password($GLOBALS['ssh2connection'],$GLOBALS['ssh2user'],$GLOBALS['ssh2passwd'])) {
	        die("unable to authorize");
	}
	$GLOBALS['ssh2host'] = $ip;
	return $GLOBALS['ssh2connection'];
}
/******* Generate random picture for the page ************/
function setPic(){

	srand((double)microtime()*1000000); 
	$handle = opendir('pics');
	$files = array();
	$n = 0;
	while (false !== ($file = readdir($handle))) {
		if (strlen($file) > 3)
			$files[$n++] = $file;
   	}
	$number = count ($files);
	$id = rand(0,$number-1);
	$path = "pics/".$files[$id];
	$GLOBALS['image'] = "<img width=150 height=250 src=\"".$path."\"/>";
}

?>
