#!/usr/bin/env perl
# PODNAME: data-embed
# ABSTRACT: embed/extract files to/from container files
use strict;
use warnings;
use Carp;
use Pod::Usage qw< pod2usage >;
use Getopt::Long qw< :config gnu_getopt >;
use English qw< -no_match_vars >;

use Data::Embed qw< :all >;
use Log::Log4perl::Tiny qw< :easy >;
Log::Log4perl->easy_init({level => $INFO, layout => '[%d %-5p] %m%n'});

my %config = ();
GetOptions(
   \%config,
   qw<
     usage! help! man! version!
     data|text|d=s
     file|filename|f=s
     name|n=s
     output|o=s
     >
) or pod2usage(-verbose => 99, -sections => 'USAGE');

if ($config{version}) {
   local $/;
   my $pod = <DATA>;
   my ($version) = $pod =~ m{=head1 \s+ VERSION \s+ version \s+(\S+)}mxs;
   pod2usage(message => "$0 $version", -verbose => 99, -sections => ' ');
} ## end if ($config{version})
pod2usage(-verbose => 99, -sections => 'USAGE') if $config{usage};
pod2usage(-verbose => 99, -sections => 'USAGE|EXAMPLES|OPTIONS')
  if $config{help};
pod2usage(-verbose => 2) if $config{man};

# Script implementation here
defined(my $action = shift @ARGV)
or pod2usage(
   message   => "no action specified",
   -verbose  => 99,
   -sections => 'USAGE',
);
my $sub = __PACKAGE__->can('action_' . $action)
  or pod2usage(
   message   => "action $action is not supported",
   -verbose  => 99,
   -sections => 'USAGE',
  );
$sub->(\%config, \@ARGV);
exit 0;

sub action_add {
   my ($cfg, $argv) = @_;

   defined(my $target = shift @$argv)
      or pod2usage(
         message   => "action add requires container file",
         -verbose  => 99,
         -sections => 'USAGE',
      );

   my $name = $cfg->{name};
   my $input;
   if (exists $cfg->{data}) {
      return embed($target, name => $name, data => $cfg->{data});
   }
   elsif (exists $cfg->{file}) {
      $input = $cfg->{file};
   }
   elsif ((! scalar @$argv) || ($argv->[0] eq '-')) {
      return embed($target, name => $name, fh => \*STDIN);
   }
   else {
      $input = $argv->[0];
   }
   $name = $input unless defined $name;
   return embed($target, name => $name, filename => $input);
}

sub action_list {
   my ($cfg, $argv) = @_;

   defined(my $target = shift @$argv)
      or pod2usage(
         message   => "action list requires container file",
         -verbose  => 99,
         -sections => 'USAGE',
      );

   my @files = embedded($target);
   if (!@files) {
      WARN "file '$target' does not have any embedded file";
      return;
   }
   my $padding = length(scalar @files);
   for my $id (0 .. $#files) {
      printf "[%${padding}d] %s\n", $id, $files[$id]->{name};
   }

   return;
}

sub action_extract {
   my ($cfg, $argv) = @_;

   defined(my $target = shift @$argv)
      or pod2usage(
         message   => "action extract requires container file",
         -verbose  => 99,
         -sections => 'USAGE',
      );
   defined(my $id = shift @$argv)
      or pod2usage(
         message   => "action extract requires identifier of wanted file",
         -verbose  => 99,
         -sections => 'USAGE',
      );
   LOGDIE "invalid identifier '$id'"
      unless $id =~ m{\A(?: 0 | [1-9]\d* )\z}mxs;

   # get hold of the input
   my @files = embedded($target);
   my $max_id = $#files;
   LOGDIE "invalid identifier $id (greater than $max_id)"
      if $id > $max_id;
   my $ifh = $files[$id]->fh();

   # get output channel if defined differently from "-"
   my $ofh = \*STDOUT;
   if (defined($cfg->{output}) && ($cfg->{output} ne '-')) {
      open my $fh, '>', $cfg->{output}
         or LOGDIE "open('$cfg->{output}'): $OS_ERROR";
      $ofh = $fh;
   }
   binmode $ofh;

   while (! eof $ifh) {
      defined(my $nread = read $ifh, my $buffer, 4096)
         or LOGDIE "read(): $OS_ERROR";
      last unless $nread; # paranoid
      print {$ofh} $buffer;
   }

   return;
}

__END__

=pod

=encoding UTF-8

=head1 NAME

data-embed - embed/extract files to/from container files

=head1 VERSION

version 0.1

=head1 DESCRIPTION

=head1 USAGE

   data-embed [--usage] [--help] [--man] [--version]

   data-embed

=head1 EXAMPLES

   shell$ data-embed

=for l'autore, da riempire:
   Qualche breve esempio con codice che mostri l'utilizzo più comune.
   Questa sezione sarà quella probabilmente più letta, perché molti
   utenti si annoiano a leggere tutta la documentazione, per cui
   è meglio essere il più educativi ed esplicativi possibile.

=for l'autore, da riempire:
   Fornite una descrizione completa del modulo e delle sue caratteristiche.
   Aiutatevi a strutturare il testo con le sottosezioni (=head2, =head3)
   se necessario.

=head1 OPTIONS

=for l'autore, da riempire:
   Una descrizione di tutte le opzioni possibili nella chiamata allo script

=over

=item --help

print a somewhat more verbose help, showing usage, this description of
the options and some examples from the synopsis.

=item --man

print out the full documentation for the script.

=item --usage

print a concise usage line and exit.

=item --version

print the version of the script.

=back

=head1 DIAGNOSTICS

=for l'autore, da riempire:
   Elencate qualunque singolo errore o messaggio di avvertimento che
   lo script può generare, anche quelli che non "accadranno mai".
   Includete anche una spiegazione completa di ciascuno di questi
   problemi, una o più possibili cause e qualunque rimedio
   suggerito.

=over

=item C<< Error message here, perhaps with %s placeholders >>

[Descrizione di un errore]

=item C<< Another error message here >>

[Descrizione di un errore]

[E così via...]

=back

=head1 CONFIGURATION AND ENVIRONMENT

=for l'autore, da riempire:
   Una spiegazione completa di qualunque sistema di configurazione
   utilizzato dallo script, inclusi i nomi e le posizioni dei file di
   configurazione, il significato di ciascuna variabile di ambiente
   utilizzata e proprietà che può essere impostata. Queste descrizioni
   devono anche includere dettagli su eventuali linguaggi di configurazione
   utilizzati.

data-embed requires no configuration files or environment variables.

=head1 DEPENDENCIES

=for l'autore, da riempire:
   Una lista di tutti i moduli su cui si basa questo script,
   incluse eventuali restrizioni sulle relative versioni, ed una
   indicazione se il modulo in questione è parte della distribuzione
   standard di Perl, parte della distribuzione del modulo o se
   deve essere installato separatamente.

None.

=head1 BUGS AND LIMITATIONS

=for l'autore, da riempire:
   Una lista di tutti i problemi conosciuti relativi al modulo,
   insime a qualche indicazione sul fatto che tali problemi siano
   plausibilmente risolti in una versione successiva. Includete anche
   una lista delle restrizioni sulle funzionalità fornite dal
   modulo: tipi di dati che non si è in grado di gestire, problematiche
   relative all'efficienza e le circostanze nelle quali queste possono
   sorgere, limitazioni pratiche sugli insiemi dei dati, casi
   particolari che non sono (ancora) gestiti, e così via.

No bugs have been reported.

Please report any bugs or feature requests through http://rt.cpan.org/

=head1 AUTHOR

Flavio Poletti C<polettix@cpan.org>

=head1 LICENCE AND COPYRIGHT

Copyright (c) 2014, Flavio Poletti C<polettix@cpan.org>. All rights reserved.

This script is free software; you can redistribute it and/or
modify it under the same terms as Perl itself. See L<perlartistic>
and L<perlgpl>.

Questo script è software libero: potete ridistribuirlo e/o
modificarlo negli stessi termini di Perl stesso. Vedete anche
L<perlartistic> e L<perlgpl>.

=head1 DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

=head1 NEGAZIONE DELLA GARANZIA

Poiché questo software viene dato con una licenza gratuita, non
c'è alcuna garanzia associata ad esso, ai fini e per quanto permesso
dalle leggi applicabili. A meno di quanto possa essere specificato
altrove, il proprietario e detentore del copyright fornisce questo
software "così com'è" senza garanzia di alcun tipo, sia essa espressa
o implicita, includendo fra l'altro (senza però limitarsi a questo)
eventuali garanzie implicite di commerciabilità e adeguatezza per
uno scopo particolare. L'intero rischio riguardo alla qualità ed
alle prestazioni di questo software rimane a voi. Se il software
dovesse dimostrarsi difettoso, vi assumete tutte le responsabilità
ed i costi per tutti i necessari servizi, riparazioni o correzioni.

In nessun caso, a meno che ciò non sia richiesto dalle leggi vigenti
o sia regolato da un accordo scritto, alcuno dei detentori del diritto
di copyright, o qualunque altra parte che possa modificare, o redistribuire
questo software così come consentito dalla licenza di cui sopra, potrà
essere considerato responsabile nei vostri confronti per danni, ivi
inclusi danni generali, speciali, incidentali o conseguenziali, derivanti
dall'utilizzo o dall'incapacità di utilizzo di questo software. Ciò
include, a puro titolo di esempio e senza limitarsi ad essi, la perdita
di dati, l'alterazione involontaria o indesiderata di dati, le perdite
sostenute da voi o da terze parti o un fallimento del software ad
operare con un qualsivoglia altro software. Tale negazione di garanzia
rimane in essere anche se i dententori del copyright, o qualsiasi altra
parte, è stata avvisata della possibilità di tali danneggiamenti.

Se decidete di utilizzare questo software, lo fate a vostro rischio
e pericolo. Se pensate che i termini di questa negazione di garanzia
non si confacciano alle vostre esigenze, o al vostro modo di
considerare un software, o ancora al modo in cui avete sempre trattato
software di terze parti, non usatelo. Se lo usate, accettate espressamente
questa negazione di garanzia e la piena responsabilità per qualsiasi
tipo di danno, di qualsiasi natura, possa derivarne.

=head1 AUTHOR

Flavio Poletti <polettix@cpan.org>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2014 by Flavio Poletti <polettix@cpan.org>

This module is free software.  You can redistribute it and/or
modify it under the terms of the Artistic License 2.0.

This program is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.

=cut
