#!/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{
	Adds an external source to the Vo. Vo id or short name and external source id or name are required fields.
	------------------------------------
	Available options:
	--voId          | -v vo id
	--voShortName   | -V vo short name
	--extSourceId   | -e external source id
	--extSourceName | -E external source name
	--batch         | -b batch
	--help          | -h prints this help

	};
}

my ($voId, $voShortName, $extSourceId, $extSourceName, $batch);
GetOptions ("help|h"  => sub {
		print help();
		exit 0;
	}, "batch|b"      => \$batch,
	"voId|v=i"        => \$voId, "voShortName|V=s" => \$voShortName,
	"extSourceId|e=i" => \$extSourceId, "extSourceName|E=s" => \$extSourceName) || die help();

# Check options
unless (defined($voShortName) or defined($voId)) {die "ERROR: voId or voShortName is required\n";}
unless (defined($extSourceName) or defined($extSourceId)) {die "ERROR: extSourceId or extSourceName is required\n";}

my $agent = Perun::Agent->new();
my $vosAgent = $agent->getVosAgent;
my $extSourcesAgent = $agent->getExtSourcesAgent;

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

if (!defined($extSourceId)) {
	my $extSource = $extSourcesAgent->getExtSourceByName( name => $extSourceName );
	$extSourceId = $extSource->getId;
}

$extSourcesAgent->addExtSource( vo => $voId, source => $extSourceId );

printMessage("External source Id:$extSourceId successfully added to the Vo Id:$voId", $batch);
