#!/usr/bin/perl -w

use strict;
use File::Glob qw/:glob/;
use File::Basename;
use File::Copy;
use Data::Dump qw/pp dump/;
use LWP::Simple; 
use List::Util qw/maxstr max/;
use Config::General;
use Text::SimpleTable;
use Text::Wrap;

$Text::Wrap::columns = 78;
$Text::Wrap::separator = "\n ";
my %indexes  = ();

my %cfg = Config::General->new( -ConfigFile => 'packages.cfg' )->getall;

#--- switch off buffering
$|++;

#----------------------------------------------------------------------------
# add/update packages & numbers to debian/control file
#----------------------------------------------------------------------------
sub control($$)
{    
	my ($files, $config) = @_;
	my $control = '../debian/control';
	my $output = '';
	my $copyright  = '../debian/copyright';
	my $coutput = $config->{'debcopystart'}."\n";
	
	open( FD, '<', $control ) or die "Cannot open $control\n";
	my @lines = <FD>;
	close( FD );
			
	for my $line (@lines)
	{	
		$output .= $line;
		if ($line =~ /Currently the following modules are included/)
		{
			
			for my $file (@$files)
			{
				my ($dir, $base, $version, $suffix) = $file =~ m!(\d+)/(.+)\-([\d\.]+)(\.tar\.gz)!;
				my $key = $base;
				$base =~ s/\-/::/g;
				$output .= qq{ .\n $base\n };
				
				#--- get data from config file and prepare output
				if (defined $config->{$key}->{'description'})
				{
					$output .= wrap("","",$config->{$key}->{'description'})."\n";
				}
				else
				{
					print "$key not exist in config file or has not defined 'description' section\n";					
					exit(1);
				}
				if (defined $config->{$key}->{'copyright'})
				{
					$coutput .= qq{\nFiles: tarballs/$file\n};
					$coutput .= qq{Copyright:};
					if (ref $config->{$key}->{'copyright'} eq 'ARRAY')
					{
						foreach my $copyright (@{$config->{$key}->{'copyright'}})
						{
							$coutput .= qq{ $copyright\n};
						}
					}
					else
					{
						$coutput .= qq{ $config->{$key}->{'copyright'}\n};
					}
				}
				else
				{
					print "$key not exist in config file or has not defined 'copyright' section\n";					
					exit(1);
				}
				if (defined $config->{$key}->{'maintainer'})
				{
					$coutput .= qq{X-Upstream-Maintainers:};
					if (ref $config->{$key}->{'maintainer'} eq 'ARRAY')
					{
						foreach my $maintainer (@{$config->{$key}->{'maintainer'}})
						{
							$coutput .= qq{ $maintainer\n};
						}
					}
					else
					{
						$coutput .= qq{ $config->{$key}->{'maintainer'}\n};
					}
				}
				else
				{
					print "$key not exist in config file or has not defined 'maintainer' section\n";					
					exit(1);
				}
				$coutput .= qq{License: Artistic or GPL-1+\n};
				if (defined $config->{$key}->{'comment'})
				{
					$coutput .= qq{X-Comment:};
					if (ref $config->{$key}->{'comment'} eq 'ARRAY')
					{
						foreach my $comment (@{$config->{$key}->{'comment'}})
						{
							$coutput .= qq{ $comment\n};
						}
					}
					else
					{
						$coutput .= qq{ $config->{$key}->{'comment'}\n};
					}
				}
			}
			last;
		}				
	}
	$coutput .= "\n".$config->{'debcopyright'}."\n";
	open( FD, '>', $control.".new" ) or die "Cannot open $control.new\n";
	print FD $output;
	close( FD );
	move($control.".new", $control);

	open( FD, '>', $copyright ) or die "Cannot open $copyright\n";
	print FD $coutput;
	close( FD );
}

#----------------------------------------------------------------------------
# check upstream versions
#----------------------------------------------------------------------------
sub check($$)
{
	my ($files, $config) = @_;
	my @urls = ();
	my %seen;

	my $table = Text::SimpleTable->new([3, 'Dir'], [50, 'Module'], [10, 'Debian'], [10, 'Upstream'], [30, 'Comment']);

	for my $file (@$files)
	{
		my $current_version = 0;
		my $upstream_version = 'missing';
		my $upstream_link = "";		
	
		#--- check package's current version 
		my ($dir, $base, $version, $suffix) = $file =~ m!(\d+)/(.+)\-([\d\.]+)(\.tar\.gz)!;		
		
		$current_version = $version;
		#--- check if watch exist, read url	
		if (defined $config->{$base}->{'watch'})
		{
			my $url = $config->{$base}->{'watch'};
			
			#--- get "directory" part & "file" part
			my ($u_dir, $u_file) = $url =~ m!(.+/)(.+)$!;
			
			#--- now take index file with directories								
			unless (defined($indexes{$u_dir}))
			{
				#--- cache result
				$indexes{$u_dir} = get($u_dir);
			}
							
			my @found = $indexes{$u_dir} =~ m!$u_file!g;
			$upstream_version = maxstr(@found);
			my @links = $indexes{$u_dir} =~ m!"(/CPAN/.+$base-$upstream_version.+)"!;
			$upstream_link = qq{http://search.cpan.org$links[0]}; 
		}
		else
		{
			print "$file not exist in config file or has not defined 'watch' section\n";
			exit(1);
		}
		
		my $comment;
		$comment = "up to date" if ($current_version == $upstream_version);
		$comment = "newer than upstream version!" if ($current_version > $upstream_version);
		if ($current_version < $upstream_version)		
		{
			$comment =  "new upstream version!";
			push @urls,	qq{$dir $upstream_link};
		}
		$table->row($dir, $base, $current_version, $upstream_version, $comment);
		$seen{$base}++;		
	}	

	print $table->draw;
	if (scalar@urls)
	{
		for my $url (@urls)
		{
			print $url."\n";
		}
	}
	foreach my $key (keys %seen)
	{
		if ($seen{$key} > 1)
		{
			print qq{$key is more than once in directory!\n}; 
		}
	}
}

if (defined($ARGV[0]))
{
	if ($ARGV[0] eq 'control')
	{
		#--- add/update packages & numbers to debian/control file
		my @f = bsd_glob('??/*.tar.gz');
		control( \@f, \%cfg );
	}	
}
else
{
	#--- check upstream versions
	my @f = bsd_glob('??/*.tar.gz');
	check( \@f, \%cfg );
}

