#!/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}->{'author'}) {
                    $coutput .= qq{\n* $base\n};
                    if (ref($config->{$key}->{'author'}) eq 'ARRAY') {
                        $coutput .= qq{\nAuthors:\n};
                        foreach  my $author (@{$config->{$key}->{'author'}}) {
                            $coutput .= qq{\t$author\n};
                        }
                    }
                    else {
                        $coutput .= 
                            qq{\nAuthor:\n\t$config->{$key}->{'author'}\n};
                    }
                }
                else {
                    print "$key not exist in config file or has not defined 'author' section\n";					
                    exit(1);
                }
                if (defined $config->{$key}->{'copyright'}) {
                    if (ref($config->{$key}->{'copyright'}) eq 'ARRAY') {
                        foreach  my $copyright (@{$config->{$key}->{'copyright'}}) {
                            $coutput .= qq{\t$copyright\n};
                        }
                    }
                    else {
                        $coutput .= "\n ".wrap("", "", $config->{$key}->{'copyright'})."\n";
                        $coutput .= "\n ".wrap("", "", $config->{'debcopyinfo'})."\n";
                    }
                }
            }
            last;
        }				
    }
    $coutput .= "\n".$config->{'debcopyright'};
    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'], [20, '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
                print "Getting $u_dir...";
                $indexes{$u_dir} = get($u_dir);
                print "Done\n";
            }

            my @found = $indexes{$u_dir} =~ m!$u_file!g;
            $upstream_version = maxstr(@found);
            $upstream_link = qq{$u_dir/$base-$upstream_version.tar.gz}; 
        }
        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 );
}
