#!/usr/bin/perl
# $Id: oarresume 918 2007-10-16 18:35:26Z capitn $
# resume a job --> it will be rescheduled

use strict;
use warnings;
use Data::Dumper;
use DBI();
use oar_iolib;
use oar_conflib qw(init_conf dump_conf get_conf is_conf);
use oar_Tools;
use oarversion;
use Getopt::Long;

my $Old_umask = sprintf("%lo",umask());
umask(oct("022"));

sub usage {
    print <<EOS;
Usage: $0 [job_ids][--sql "sql syntax"][-V][-h] 
Ask OAR to change job_ids states into Waiting when it is Hold or in Running
if it is Suspended.
      --sql     resume jobs which respond to the SQL where clause on the table
                jobs (ex: "project = 'p1'")
  -h, --help    show this help screen
  -V, --version print OAR version number
EOS
}

my $Version;
my $Help;
my $Sql_property;

GetOptions (
    "version|V" => \$Version,
    "sql=s"   => \$Sql_property,
    "help|h" => \$Help
           );

if (defined($Help)){
    usage();
    exit(0);
}

if (defined($Version)){
    print("OAR version : ".oarversion::get_version()."\n");
    exit(0);
}

if (($#ARGV < 0) and (!defined($Sql_property))){
    usage();
    exit(1);
}

init_conf($ENV{OARCONFFILE});
my $remote_host = get_conf("SERVER_HOSTNAME");
my $remote_port = get_conf("SERVER_PORT");

my @job_ids;
my $exit_code = 0;
foreach my $j (@ARGV){
    if ($j =~ /^\d+$/){
        push(@job_ids, $j);
    }else{
        warn("[ERROR] \"$j\" is not a valid job identifier\n");
        $exit_code = 2;
    }
}

if (defined($Sql_property)){
    my $db = iolib::connect_ro();
    foreach my $j (iolib::get_jobs_with_given_properties($db,$Sql_property)){
        push(@job_ids, $j->{job_id});
    }
    iolib::disconnect($db);
}

my $base = iolib::connect();

foreach my $j (@job_ids){
    my $err = iolib::resume_job($base,$j);
    if ($err != 0) {
        my $str = "/!\\ Cannot resume $j :";
        if ($err == -1){
            warn("$str this job does not exist.\n");
        }elsif ($err == -2){
            warn("$str you are not the right user.\n");
        }elsif ($err == -3){
            warn("$str the job is not in the Hold or Suspended state.\n");
        }elsif ($err == -4){
            warn("$str only oar or root user can resume Suspended jobs.\n");
        }else{
            warn("$str unknown reason.\n");
        }
        $exit_code = 1;
    }else{
        print("[$j] Resume request was sent to the OAR server.\n");
    }
}
iolib::disconnect($base);
#Signal Almigthy
oar_Tools::notify_tcp_socket($remote_host,$remote_port,"ChState");

exit($exit_code);
