#!/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{
	Assigns a group to a resource. 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 assigns group asynchronously
	--inactive    | -i assigns group as inactive
	--subgroups   | -s assigns group's subgroups automatically
	--batch       | -b batch
	--help        | -h prints this help

	};
}

my ($groupId, $groupName, $voId, $voShortName, $resourceId, $async, $inactive, $subgroups, $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,
	"inactive|i" => \$inactive, "subgroups|s" => \$subgroups) || 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";}

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;
}

if (defined($async)) {
	$async = 1;
} else {
	$async = 0;
}

if (defined($inactive)) {
	$inactive = 1;
} else {
	$inactive = 0;
}

if (defined($subgroups)) {
	$subgroups = 1;
} else {
	$subgroups = 0;
}
$resourcesAgent->assignGroupToResource(group => $groupId, resource => $resourceId, async => $async,
	assignInactive => $inactive, autoAssignSubgroups => $subgroups );

printMessage("Group Id: $groupId successfully assigned to the resource Id:$resourceId", $batch);
