#!/usr/bin/perl
#

use strict;
use warnings;
use Data::Dumper;
use DBI();
use OAR::IO;

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

sub usage() {
    print <<EOS;
Usage: oarremoveresource resource_number
WARNING: this command removes all records in the database
about "resource_number".

So you will loose this resource history and jobs executed on this one
EOS
    exit(1);
}

usage if ((@ARGV < 1) || !($ARGV[0] =~ /^\d+$/));

my $Resource = $ARGV[0];
print "Resource to remove: $Resource\n";

my $exit_code = 0;

my $base = OAR::IO::connect();
OAR::IO::lock_table(
    $base,
    [   "resources", "resource_logs", "assigned_resources", "jobs",
        "frag_jobs", "event_logs",    "event_log_hostnames"
    ]);

my $resource_ref = OAR::IO::get_resource_info($base, $Resource);
if (defined($resource_ref->{state}) && ($resource_ref->{state} eq "Dead")) {
    my $req = <<EOS;
SELECT jobs.job_id, jobs.assigned_moldable_job
FROM assigned_resources, jobs
WHERE
    assigned_resources.resource_id = $Resource
    AND assigned_resources.moldable_job_id = jobs.assigned_moldable_job
EOS

    my $sth = $base->prepare($req);
    $sth->execute();
    my @jobList;
    while (my @ref = $sth->fetchrow_array()) {
        push(@jobList, [ $ref[0], $ref[1] ]);
    }
    $sth->finish();
    foreach my $i (@jobList) {
        print("\tRemove the job $i->[0], it was run on the resource $Resource\n");
        $base->do("DELETE from event_logs         WHERE job_id = $i->[0]");
        $base->do("DELETE from frag_jobs          WHERE frag_id_job = $i->[0]");
        $base->do("DELETE from jobs               WHERE job_id = $i->[0]");
        $base->do("DELETE from assigned_resources WHERE moldable_job_id = $i->[1]");
    }
    $base->do("DELETE from assigned_resources     WHERE resource_id = $Resource");
    $base->do("DELETE from resource_logs          WHERE resource_id = $Resource");
    $base->do("DELETE from resources              WHERE resource_id = $Resource");
    print("Resource $Resource removed.\n");
} else {
    print("/!\\ The state of the resource $Resource must be set to Dead before.\n");
    $exit_code = 2;
}

OAR::IO::unlock_table($base);
OAR::IO::disconnect($base);

exit($exit_code);
