#!/usr/bin/perl -w

use strict;

use constant VERSION_NUMBER => "1.0";
use constant RELEASE_DATE => "2016-06-27";
use constant TRUE => (1==1);
use constant FALSE => (1==0);

use File::Basename;
use File::Spec;
use Getopt::Long;
use File::Path qw(make_path remove_tree);
use XML::Simple;

my %cmdoptions = ();

sub usage($) {
	print STDERR "usage:\n";
	print STDERR basename($_[0])." <path_to_artifact.jar>\n";
	exit(1);
}

if (!GetOptions('v' => \$cmdoptions{'verbose'},
		'version' => \$cmdoptions{'version'},
                )) {
	usage($0);
}

if ($cmdoptions{'version'}) {
	print basename($0)." ".VERSION_NUMBER." (".RELEASE_DATE.")\n";
	exit(0);
}

if (!@ARGV || !$ARGV[0]) {
	usage($0);
}

my $archiveFile = $ARGV[0];
my $directory = File::Spec->catfile('.', 'tmp');

make_path($directory);
system("unzip", "-q", "-d", "$directory", "$archiveFile");

my $fn = File::Spec->catfile($directory, 'artifacts.xml');
my $dom = XMLin($fn, KeyAttr => []);

remove_tree($directory);

my %artifacts = ();

if ($dom->{'artifacts'}{'artifact'}) {
	foreach my $node (@{$dom->{'artifacts'}{'artifact'}}) {
		my $name = $node->{'id'} . "_" . $node->{'version'} . ".jar";
		$artifacts{$name} = TRUE;
	}
}

my $repository = File::Spec->catfile(dirname($ARGV[0]), 'plugins');
local *DIR;
opendir(*DIR, $repository);
while (my $file = readdir(*DIR)) {
	if ($file ne '.' && $file ne '..' && $file =~ /\.jar$/) {
		if (!$artifacts{$file}) {
			my $fn = File::Spec->catfile($repository, $file);
			unlink($fn) or die("$fn: $!\n");
		}
	}
}
closedir(*DIR);

exit(0);
