#!/usr/bin/perl
use strict;
use warnings;
use Locale::Maketext::Extract;
use Locale::Maketext::Extract::Plugin::Xslate;
use File::Find::Rule;
use File::Spec;
use Getopt::Long;
use Pod::Usage;

GetOptions(
    'help'     => \my $help,
    'po-dir=s' => \my $po_dir,
    'version'  => \my $version,
) or pod2usage(1);

if ($version) {
    require Amon2::Plugin::L10N;
    print "Amon2::Plugin::L10N: $Amon2::Plugin::L10N::VERSION\n";
    exit(0);
}
pod2usage(0) if $help;

@ARGV or pod2usage(1);
$po_dir ||= 'po';

my $extract = Locale::Maketext::Extract->new(
    plugins  => {
        perl => [qw/pl pm js/],
        xslate  => {
            syntax     => 'TTerse',
            extensions => [qw/ tt /],
        },
    },
    warnings => 1,
    verbose  => 1,
    header   => << 'POT',
# GENERATED BY amon2-xgettext.pl (Amon2::Plugin::L10N)
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: YEAR-MO-DA HO:MI+ZONE\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
POT
);

mkdir $po_dir;
for my $lang (@ARGV) {
    my $file = File::Spec->catfile($po_dir, "$lang.po");
    $extract->read_po($file) if -f $file;

    $extract->extract_file($_) for (
        File::Find::Rule->file()->name(qr/.*\.(?:pm|pl)/)->in('lib'),
        File::Find::Rule->file()->name('*.tt')->in('tmpl')
    );

    $extract->compile(1);
    $extract->write_po($file);
}
__END__

=encoding utf-8

=head1 NAME

amon2-xgettext.pl - .po file generater for Amon2 applications

=head1 USAGE

  $ amon2-xgettext.pl en ja zh-tw zh-cn fr
  $ ls ./po/
  en.po ja.po zh-tw.po zh-cn.po fr.po

  $ amon2-xgettext.pl --po-dir=translate en ja zh-tw zh-cn fr
  $ ls ./translate/
  en.po ja.po zh-tw.po zh-cn.po fr.po

  $ amon2-xgettext.pl --help
  $ amon2-xgettext.pl --version

=head1 AUTHOR

Kazuhiro Osawa E<lt>yappo {at} shibuya {dot} plE<gt>

=head1 COPYRIGHT

Copyright 2013- Kazuhiro Osawa

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 SEE ALSO

L<Amon2::Plugin::L10N>

=cut
