#!/usr/bin/perl

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

sub help {
	return qq{
	Sets the member group attribute. Group, VO, attribute value and attribute id fields are required.
	--------------------------------------
	Available options:
	--groupId         | -g group id
	--groupName       | -G group name
	--voId            | -v vo id
	--voShortName     | -V vo short name
	--memberId        | -m member id
	--attributeId     | -a attribute id
	--attributeName   | -A attribute name including namespace
	--attributeValue  | -w attribute value
	--batch           | -b batch
	--help            | -h prints this help

	};
}

my ($groupId, $groupName, $voId, $voShortName, $memberId, $attributeId, $attributeName, @attributeValue);
our $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,
	"attributeId|a=i"   => \$attributeId,
	"attributeName|A=s" => \$attributeName, 'attributeValue|w=s@{1,}' => \@attributeValue,
	"memberId|m=i"      => \$memberId) || 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($memberId)) { die "ERROR: memberId is required \n";}
unless (defined($attributeId) or defined($attributeName)) { die "ERROR: attributeId or attributeName is required \n";}
unless (@attributeValue) { die "ERROR: attributeValue is required \n";}

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

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

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

my $attributesAgent = $agent->getAttributesAgent;
my $attributeDefinition;

if (!defined($attributeId)) {
	$attributeDefinition = $attributesAgent->getAttributeDefinition( attributeName => $attributeName );
} else {
	$attributeDefinition = $attributesAgent->getAttributeDefinitionById( id => $attributeId );
}

# Get the attribute definition and create the attribute
my $attribute = Perun::beans::Attribute->fromAttributeDefinition( $attributeDefinition );

$attribute->setValueFromArray( @attributeValue );

$attributesAgent->setAttribute( member => $memberId, group => $groupId, attribute => $attribute );

printMessage("Attribute Id:".$attribute->getId." set for the group Id:$groupId and member Id:$memberId", $batch);
