#!/usr/local/bin/perl -w
 
use DBI;
use lib qw(/home/lukacm/crontab);
require "/home/lukacm/prec/ssh2compute.inc.pl";

$dbserver = $dbserver;
$db = $db;
$dbpwd = $dbpwd;
$dbuser = $dbuser;
$machinetable = $machinetable;
$home = $ENV{'HOME'};


if (not $ARGV[0]) {
	print ("Missing parameters\n");
	exit(0);
}

my $date = $ARGV[0];
my $dbh = DBI->connect("DBI:mysql:$db:$dbserver","$dbuser","$dbpwd");

my $query =  "SELECT dlocation FROM $jobtable WHERE submitdate='$date'";
my $table_data = $dbh->prepare($query);
$table_data->execute;
# assign fields to variables
$table_data->bind_columns(\$dlocation);
# output name list to the browser
$table_data->fetch();

$home = $home.'/'.$dlocation;
print $home."   ".$dlocation;
chdir $home;

#get the name of the job
$query =  "SELECT command FROM $jobtable WHERE submitdate='$date'";
$table_data = $dbh->prepare($query);
$table_data->execute;
# assign fields to variables
$table_data->bind_columns(\$command);
# output name list to the browser
$table_data->fetch();

#update the state to running
$query =  "update $jobtable SET state='1' where submitdate='$date'";
$table_data = $dbh->prepare($query);
$table_data->execute;


# get the machine id
$query =  "SELECT remote_machines_id FROM $jobtable WHERE submitdate='$date'";
$table_data = $dbh->prepare($query);
$table_data->execute;
# assign fields to variables
$table_data->bind_columns(\$remote_machine_id);
$table_data->fetch();


# get the state
$query =  "SELECT state FROM $machinetable WHERE id='$remote_machine_id'";
$table_data = $dbh->prepare($query);
$table_data->execute;
# assign fields to variables
$table_data->bind_columns(\$state);
$table_data->fetch();

$state = $state +1;

$query =  "update remote_machines SET state='$state' where id='$remote_machine_id'";

$table_data = $dbh->prepare($query);
$table_data->execute;

#execute the command

my $out = `$command`;

$state = $state -1;
#put the state of the machine back one level bellow
$query =  "update remote_machines SET state='$state' where id='$remote_machine_id'";
$table_data = $dbh->prepare($query);
$table_data->execute;

#update the application state to stoped
$query =  "update $jobtable SET state='0' where submitdate='$date'";
$table_data = $dbh->prepare($query);
$table_data->execute;

$table_data->finish();

# disconnect from database
$dbh->disconnect;

exit;
