#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case);
use Perun::Agent;
use Perun::Common qw(printMessage);

sub help {
	return qq{
	Tries to activate the group-resource status. If the async is not set, the validation is performed synchronously.
	Resource id and group id or group name together with vo id or vo short name are required fields.
	------------------------------------
	Available options:
	--groupId     | -g group id
	--groupName   | -G group name
	--voId        | -v vo id
	--voShortName | -V vo short name
	--resource    | -r resource id
	--async       | -a async mode
	--batch       | -b batch
	--help        | -h prints this help

	};
}

my ($groupId, $groupName, $voId, $voShortName, $resourceId, $async, $batch);
GetOptions ("help|h" => sub {
	print help();
	exit 0;
}, "batch|b"     => \$batch,
	"groupId|g=i"    => \$groupId, "groupName|G=s" => \$groupName,
	"voId|v=i"       => \$voId, "voShortName|V=s" => \$voShortName,
	"resourceId|r=i" => \$resourceId,
	"async|a" => \$async) || die help();

# Check options
unless (defined($groupId) or ((defined($voShortName) or defined($voId)) and defined($groupName))) {die "ERROR: groupId or groupName and voId or voShortName is required\n";}
unless (defined($resourceId)) {die "ERROR: resourceId is required\n";}
if (defined($async)) {
	$async = 1;
} else {
	$async = 0;
}

my $agent = Perun::Agent->new();
my $vosAgent = $agent->getVosAgent;
my $groupsAgent = $agent->getGroupsAgent;
my $resourcesAgent = $agent->getResourcesAgent;

if (!defined($groupId)) {
	if (!defined($voId)) {
		my $vo = $vosAgent->getVoByShortName( shortName => $voShortName );
		$voId = $vo->getId;
	}

	my $group = $groupsAgent->getGroupByName( vo => $voId, name => $groupName );
	$groupId = $group->getId;
}

$resourcesAgent->activateGroupResourceAssignment(group => $groupId, resource => $resourceId, async => $async );

printMessage("Group Id: $groupId activated on the resource Id:$resourceId", $batch);
