#!/usr/bin/perl

use strict;
use Carp;
use CPANPLUS;
use File::Find;
use Data::Dumper;

my $DEBUG = 0;

# Initialize CPANPLUS backend
my $cb		= CPANPLUS::Backend->new();
my $conf	= $cb->configure_object();

# Retrieve current ebuilds
my @ebuilds;

sub find_wanted {
	if ( $_ =~ m/\.ebuild \z/xms ) {
		unless ( $_ =~ m/\Acatalystframework/xms ) {
			print "    $_\n" if $DEBUG >= 2;
			push @ebuilds, $_;
		}
	}
}

find( \&find_wanted, './dev-perl');

# Skip development ebuilds
@ebuilds = grep { $_ !~ m/\A (?: [\w\-]+ ) - (?: \d+\.\d+\.\d+ ) (?: -r\d+ )? \.ebuild \z/xms } @ebuilds;

# Skip deprecated ebuilds
@ebuilds = grep { $_ !~ m/ Catalyst-\d+\.\d+ \.ebuild \z/xms } @ebuilds;

# Get only latest version
my %version_of;
print "Computing versions...\n" if $DEBUG >= 1;
for my $ebuild (@ebuilds) {
	if ( $ebuild =~ m/\A ( [\w\-]+ ) - ( \d+\.\d+ ) (?: -r\d+ )? \.ebuild \z/xms ) {
		my ($module_name, $module_version) = ($1, $2);
        	if ( (!defined $version_of{$module_name})
        		|| ($version_of{$module_name} < $module_version) )
        	{
            $version_of{$module_name} = $module_version;
	    }
    }
    else {
        warn "Malformed ebuild $ebuild\n";
    }
}

# Lookup CPAN
print "Looking up CPAN...\n" if $DEBUG >= 1;
for my $module_name (keys %version_of) {
	print "    Looking up $module_name [$version_of{$module_name}]\n" if $DEBUG >= 2;

	my $cpan_module = $cb->parse_module(
		module	=> $module_name
	);
	
	next if !defined $cpan_module;

	if ($cpan_module->package_name() ne $module_name) {
		croak "Mismatch package name";
	}

	if ( $cpan_module->package_version() ne $version_of{$module_name} ) {
		print	"$module_name: "
			.$cpan_module->package_version()
			." [ $version_of{$module_name} ]\n";
	}

}

