#!/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{
	Removes selected manager from resource.  Resource id or name and manager's id are required fields.
	------------------------------------
	Available options:
	--resourceId      | -r resource id
	--userId          | -u user id
	--authGroupId     | -a authorized groupId
	--authGroupName   | -A authorized group Name
	--authGroupVoId   | -o authorized group VO Id
	--authGroupVoName | -O authorized group VO Name
	--batch           | -b batch
	--help            | -h prints this help

	};
}

my ($resourceId, $userId, $authGroupId, $authGroupName, $authGroupVoId, $authGroupVoName,$batch);
GetOptions ("help|h"   => sub {
		print help();
		exit 0;
	}, "batch|b"       => \$batch,
	"resourceId|r=i"   => \$resourceId,
	"userId|u=i"       => \$userId,
	"authGroupId|a=i"  => \$authGroupId,
	"authGroupName|A=s"  => \$authGroupName,
	"authGroupVoId|o=i"  => \$authGroupVoId,
	"authGroupVoName|O=s"  => \$authGroupVoName
) || die help();

# Check options
unless (defined($resourceId)) { die "ERROR: resourceId is required \n";}

my $agent = Perun::Agent->new();
my $resourcesAgent = $agent->getResourcesAgent;

if (defined $userId) {
	$resourcesAgent->removeAdmin( resource => $resourceId, user => $userId );

	printMessage("Manager user Id:$userId successfully removed from the Resource Id:$resourceId", $batch);
} else {
	unless (defined $authGroupId or defined $authGroupName) { die "ERROR: authorizedGroupId or authorizedGroupName is required \n";}
	unless (defined $authGroupId) {
		unless (defined $authGroupVoId or defined $authGroupVoName) { die "ERROR: authorizedGroupVoId or authorizedGroupVoName is required \n";}

		my $groupsAgent = $agent->getGroupsAgent;
		unless (defined $authGroupVoId) {
			my $vo = $agent->getVosAgent->getVoByShortName( shortName => $authGroupVoName );
			$authGroupVoId = $vo->getId;
		}
		my $group = $groupsAgent->getGroupByName( vo => $authGroupVoId, name => $authGroupName );
		$authGroupId = $group->getId;
	}
	$resourcesAgent->removeAdmin( resource => $resourceId, authorizedGroup => $authGroupId);
	printMessage("Manager Group Id:$authGroupId successfully removed from the Resource Id:$resourceId", $batch);
}
