#!/usr/bin/perl -w

use strict;
use warnings;

use autodie;
use Archive::Tar;
use Debconf::Client::ConfModule qw(:all);
use File::Basename qw(basename);
use File::Spec::Functions qw(catfile);
use File::Temp qw(tempdir);
use Getopt::Long;
use Pod::Usage qw(pod2usage);

use constant DICT_DIR => '/usr/share/bgoffice';
use constant Q => 'bgoffice-dict-downloader/dict-list';

my $opt_ask = 1;

GetOptions(
    'ask!'  => \$opt_ask,
);

version('2.0');
fset( Q, 'seen', 'false' ) if $opt_ask;
input( 'high', Q );
my @ret = go();

if ( $ret[0] == 0 ) {
    my ( $ret, $dicts ) = get(Q);
    if ( $ret == 0 ) {
        my $dir = tempdir( CLEANUP => 1 );
        for my $dict ( split( /, /, $dicts ) ) {
            my $tar_file = catfile( $dir, $dict );
            warn "Downloading $dict\n";
            system( 'bgoffice-dict-download',
                '--dict', $dict, '--output', $tar_file )
                and next;
            warn " Extracting\n";
            my $tar = Archive::Tar->new;
            $tar->read( $tar_file, undef,
                { filter => qr{^(?:[^/]+/)?data/[^/]+$} } );
            if ( $tar->list_files ) {
                for my $f ( $tar->get_files ) {
                    warn "  ... " . $f->name . "\n";
                    $f->extract( catfile( DICT_DIR, basename( $f->name ) ) );
                }
            }
            else {
                warn " File is not a Tar archive or doesn't contain a data/ member\n";
            }
        }
    }
}

__END__

=head1 NAME

update-bgoffice-dicts - automate updating of bgoffice dictionaries

=head1 SYNOPSIS

    update-bgoffice-dicts [option...]

=head1 DESCRIPTION

B<update-bgoffice-dicts> automates the downloading and updating of bgoffice
dictionaries. It uses L<debconf(7)> to ask the user which dictionaries to
download, then invokes L<bgoffice-dict-download(1)> to download them, and
finaly extracts the files in the right directory, so that bgoffice can find
them.

The last part will fail unless B<update-bgoffice-dicts> is run as root.

=head1 OPTIONS

=over

=item --no-ask

Normally, debconf won't ask the questions that are already seen by the user.
That behaviour is disabled by default, as it is quite useful to be able to
change your dictionary selection when invoking B<update-bgoffice-dicts>. If you
want to simply re-download and unpack the dictionaries, based on a previously
made selection, use that option.

=back

=head1 COPYRIGHT AND LICENSE

=over

=item Copyright: (C) 2010 Damyan Ivanov L<dmn@debian.org>

=back

Permission is granted to use this work, with or without modifications, provided
that this notice is retained. If we meet some day, and you think this stuff is
worth it, you can buy me a beer in return.
