#!/usr/bin/perl -w

use strict;

use constant VERSION_NUMBER => "5.0";
use constant RELEASE_DATE => "2014-03-16";
use constant BUILD_MAX_COUNT => 2;
use constant TRUE => (1==1);
use constant FALSE => (1==0);

use File::Basename;
use File::Spec;
use Getopt::Long;

my @validExtensions = ( 
	'pom', # Maven project
	'jar', # Java library
	'zip', # General archive file
	'dll', 'so', 'dynlib', # Dynamic native libraries
	'apk', 'apklib', # Android
	'jnlp', 'jnlpicon', # Java remote call
	'target', # Eclipse target
	);

my %cmdoptions = (
	'maxcount' => BUILD_MAX_COUNT,
);

sub usage($) {
	print STDERR "usage:\n";
	print STDERR basename($_[0])." [-v][--test][--maxcount=<n>] <repository_directory...>\n";
	exit(1);
}

sub rm($$) {
	my $id = shift;
	my $filename = shift;
	if (-f "$filename") {
		if ($cmdoptions{'test'}) {
			if (-f "$filename") {
				print "RM  [$id] $filename\n";
			}
			else {
				print "ERR [$id] $filename\n";
			}
		}
		else {
			unlink("$filename") or die("$filename: $!\n");
		}
	}
}

sub removeFiles($$@) {
	my $id = shift;
	my $filename = shift;
	foreach my $extension (@validExtensions) {
		rm($id, "$filename.$extension");
		rm($id, "$filename.$extension.md5");
		rm($id, "$filename.$extension.sha1");
	}
	foreach my $tag (@_) {
		foreach my $extension (@validExtensions) {
			rm($id, "$filename-$tag.$extension");
        		rm($id, "$filename-$tag.$extension.md5");
	        	rm($id, "$filename-$tag.$extension.sha1");
		}
	}
}

sub matchesFile($$) {
	my $filename = shift;
	my $directory = shift;
	if ($filename) {
		if ($cmdoptions{'verbose'}) {
			print "found file $filename ";
		}
		foreach my $ext (@validExtensions) {
			if ($filename =~ /^(.*?)\-([0-9.]+)\-((?:[0-9.]+)|(?:SNAPSHOT))\-([0-9]+)\-(.+?)\Q.$ext\E$/) {
				my %description = (
					'filename' => $filename,
					'file' => File::Spec->catfile($directory, "$1-$2-$3-$4"),
					'key' => "$1-$2",
					'name' => $1,
					'version' => $2,
					'buildversion' => $3,
					'buildnumber' => $4,
					'classifiers' => [ $5 ],
					'snapshot' => ($3 eq 'SNAPSHOT'),
				);
				if ($cmdoptions{'verbose'}) {
					print "[ok]\n";
				}
				return \%description;
			}
			elsif ($filename =~ /^(.*?)\-([0-9.]+)\-((?:[0-9.]+)|(?:SNAPSHOT))\-([0-9]+)\Q.$ext\E$/) {
				my %description = (
					'filename' => $filename,
					'file' => File::Spec->catfile($directory, "$1-$2-$3-$4"),
					'key' => "$1-$2",
					'name' => $1,
					'version' => $2,
					'buildversion' => $3,
					'buildnumber' => $4,
					'classifiers' => [ ],
					'snapshot' => ($3 eq 'SNAPSHOT'),
				);
				if ($cmdoptions{'verbose'}) {
		                        print "[ok]\n";
		                }
				return \%description;
			}
		}
		if ($cmdoptions{'verbose'}) {
			print "[skipped]\n";
		}
	}
	return undef;
}

sub __compare_versions__($$) {
	my $a = shift;
	my $b = shift;
	my $lena = @{$a};
	my $lenb = @{$b};
	for(my $i=0; $i<$lena && $i<$lenb; ++$i) {
		my $cmp = $a->[$i] <=> $b->[$i];
		if ($cmp!=0) {
			return $cmp;
		}
	}
	if ($lena<$lenb) {
		return -1;
	}
	if ($lena>$lenb) {
		return 1;
	}
	return 0;
}

sub __sort_critera__($$) {
	my $a = shift;
	my $b = shift;

	$a =~ /^(.*?)\-([0-9.]+)\-((?:[0-9.]+)|(?:SNAPSHOT))\-([0-9]+)$/;
	my ($name_a,$version_a,$date_a,$buildnumber_a) = ($1,$2,$3,$4);
	$b =~ /^(.*?)\-([0-9.]+)\-((?:[0-9.]+)|(?:SNAPSHOT))\-([0-9]+)$/;
	my ($name_b,$version_b,$date_b,$buildnumber_b) = ($1,$2,$3,$4);

	my $snapa = ($date_a eq 'SNAPSHOT');
	my $snapb = ($date_b eq 'SNAPSHOT');

	if ($snapa && $snapb) {
		return $buildnumber_b <=> $buildnumber_a;
	}
	if ($snapa) {
		return -1;
	}
	if ($snapb) {
		return 1;
	}
	my @taba = split(/\./, $date_a);
	my @tabb = split(/\./, $date_b);
	my $cmp = __compare_versions__(\@tabb,\@taba);
	if ($cmp!=0) {
		return $cmp;
	}
	return $buildnumber_b <=> $buildnumber_a;
}

sub cleanReleases($) {
	my $dir = shift || die("no directory\n");
	my %files = ();
	local *DIR;
	opendir(*DIR, "$dir") or die("$dir: $!\n");
	while (my $d = readdir(*DIR)) {
		my $filename = File::Spec->catdir("$dir", "$d");
		if ($d ne '.' && $d ne '..' && -f "$filename") {
			my $description = matchesFile($d,$dir);
			if ($description && $description->{'buildversion'}
			    && $description->{'version'} && $description->{'name'}
			    && $description->{'key'}) {
				my $key = $description->{'key'};
				my $ckey = "$key-".$description->{'buildversion'}."-".$description->{'buildnumber'};
				if (!$files{"$key"}{"$ckey"}) {
					$files{"$key"}{"$ckey"} = $description;
				}
				elsif ($description->{'classifiers'}) {
					push @{$files{"$key"}{"$ckey"}{'classifiers'}}, @{$description->{'classifiers'}};
				}
		        }
		}
	}
	closedir(*DIR);
	if (%files) {
		while (my ($modulename,$versions) = each(%files)) {
			my @removedids = keys %{$versions};
			@removedids = sort __sort_critera__ @removedids;
			my @retainedids = splice @removedids, 0, $cmdoptions{'maxcount'};
			if ($cmdoptions{'test'}) {
				print "RETA ".join('|',@retainedids)."\n";
			}
			if (@removedids) {
				if ($cmdoptions{'test'}) {
					print "RMID ".join('|',@removedids)."\n";
				}
				foreach my $removedid (@removedids) {
					if ($versions->{"$removedid"}) {
						removeFiles(
							$removedid,
							$versions->{"$removedid"}{'file'},
							@{$versions->{"$removedid"}{'classifiers'}});
					}
				}
			}
		}

	}
}

sub cleanDirectory($) {
	my $dir = shift || die("no directory\n");
	my @subdirs = ($dir);
	while (@subdirs) {
		$dir = shift @subdirs;
		local *DIR;
		opendir(*DIR, "$dir") or die("$dir: $!\n");
		while (my $d = readdir(*DIR)) {
			if (($d ne File::Spec->updir())
				&&($d ne File::Spec->curdir())) {
				my $full = File::Spec->catfile("$dir","$d");
				if (-d "$full") {
					push @subdirs, "$full";
				}
			}
		}
		closedir(*DIR);

		my $mavenfile = File::Spec->catfile("$dir",'maven-metadata.xml');
		if (-f "$mavenfile") {
			if ($cmdoptions{'verbose'}) {
				print "cleaning $dir...\n";
			}
			cleanReleases($dir);
		}
	}
}

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

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

if ($cmdoptions{'maxcount'}<1) {
	$cmdoptions{'maxcount'} = 1;
}

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

foreach my $directory (@ARGV) {
	cleanDirectory("$directory");
}

exit(0);
