<?php
ini_set("display_startup_errors","1");
ini_set("display_errors","1");
error_reporting(E_ALL);


require ("ssh2server.inc.php");



/******* Init the interface  ******/
session_start(); //web side
constructor();

/******* initialize the php interface on the compute-side *********/
function constructor(){
	$id = $_REQUEST['id'];
	if ($id == 0)
		fnCleanAll();
	else
		fnCleanSingle($id);	

	$dbhost = $GLOBALS['dbhost'];
	$dbuser = $GLOBALS['dbuser'];
	$dbpass = $GLOBALS['dbpass'];
	$database = $GLOBALS['database'];
	$jobtable = $GLOBALS['jobtable'];
	$machinetable = $GLOBALS['machinetable'];
	$machinefields = $GLOBALS['MACHINE_TABLE_FIELDS'];
	
	//Create the connection to the MySQL
	$GLOBALS['dbconnection'] = mysql_connect($dbhost,$dbuser,$dbpass) or die ("Could not connect!" . mysql_error());
	mysql_select_db($database);	

	
	//Test the database and the availability of the table and stuff	
	if (!fnDatabaseExists($database)){
		$query = "CREATE DATABASE $database";
		if(mysql_query($query))
			print("Database created \n");
		else
			die ("Could not Create Database, exiting!" . mysql_error()."\n");
	}

	if (!fnTableExists($machinetable))
	{
		$fields = extractFields($machinefields);
		$query="CREATE TABLE $machinetable (".extractFields($GLOBALS['MACHINE_TABLE_FIELDS']).")";
		print($query);
		if(mysql_query($query))
			print("Table created \n");	
		else
			print ("Could not Create the Machine Table, exiting!  " . mysql_error()."\n");
	}


	if (!fnTableExists($jobtable))
	{
		$foreignkey = $machinetable."_id";
		$query="CREATE TABLE $jobtable (".extractFields($GLOBALS['JOB_TABLE_FIELDS']).")";

		if(mysql_query($query))
			print("Table created \n");	
		else
			die ("Could not Create the Jobs Table, exiting!" . mysql_error()."\n");
	}
}

 

/******* 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);
	}
}
?>
