#!/usr/bin/perl -w

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 an external source from the user. User id and external login and external source id or name are required fields
	------------------------------------
	Available options:
	--userId         | -u user id
	--extSourceId    | -e external source id
	--extSourceName  | -E external source name
	--extSourceLogin | -l external login
	--batch          | -b batch
	--help           | -h prints this help

	};
}

my ($userId,$extSourceId,$extSourceName,$extSourceLogin,$batch);
GetOptions ("help|h" => sub { print help(); exit 0;},"userId|u=i" => \$userId,
"extSourceId|e=i" => \$extSourceId, "extSourceName|E=s" => \$extSourceName,
	"extSourceLogin|l=s" => \$extSourceLogin, "batch|b" => \$batch) || die help();

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

my $agent = Perun::Agent->new();
my $usersAgent = $agent->getUsersAgent;
my $extSourcesAgent = $agent->getExtSourcesAgent;

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

my $userExtSource = $usersAgent->getUserExtSourceByExtLogin("extSource" => $extSource, "extSourceLogin" => $extSourceLogin);

$usersAgent->removeUserExtSource(user => $userId, userExtSource => $userExtSource->getId);

printMessage("External Source: $extSourceId with login: $extSourceLogin removed from user Id: $userId", $batch);
