#!/usr/bin/perl

# PODNAME: tanker_download

=encoding UTF-8
=cut

=head1 SYNOPSIS

tanker_download --project=project_id --status=approved --langs=ru,en

 Obligatory options:

      --project=project_id  # project id in the tanker
      --status=approved     # 'approved' or 'unapproved'
      --langs=ru,en         # list of languages, comma separated

 Optional options:

      --branch=feature_x        # branch name. Default is master
      --dont_delete_tmp_files   # files in ./locale/tmp will not be deleted in
                                # the end of script's work
      --dont_compile_mo         # .mo files will not be created
      --fix_po_from_tanker      # removes duplicate msgid from po files
      --help                    # show this message and exit
      --use_test_tanker         # work with tanker-test.yandex-team.ru

Script will download .po files from selected tanker project and will compile
them to .mo files. Script will create such a file structure in the folder
where it is run:

    locale/
    ├── en_US
    │   └── LC_MESSAGES
    │       └── partner.mo
    ├── ru_RU
    │   └── LC_MESSAGES
    │       └── partner.mo
    └── tmp
        ├── en.po
        └── ru.po

=cut

# common modules
use strict;
use warnings FATAL => 'all';
use 5.008;
use Carp;
use Getopt::Long;
use File::Slurp;
use Term::ANSIColor qw(:constants);
use Pod::Usage;

use Yandex::Tanker;

# global vars
# Hash key is the 'subtag' field from file http://www.iana.org/assignments/language-subtag-registry
my %LANG_CODES = (
    be => 'be_BY',
    en => 'en_US',
    kk => 'kk_KZ',
    ru => 'ru_RU',
    tr => 'tr_TR',
    uk => 'uk_UA',
);

# subs
sub get_correct_opts {

    my $help;
    my $project;
    my $status;
    my $opts_langs;
    my $dont_delete_tmp_files;
    my $dont_compile_mo;
    my $fix_po_from_tanker;
    my $use_test_tanker;
    my $branch;

    GetOptions(
        'help' => \$help,
        'project=s' => \$project,
        'status=s'  => \$status,
        'langs=s'   => \$opts_langs,
        'branch=s'   => \$branch,
        'dont_delete_tmp_files' => \$dont_delete_tmp_files,
        'dont_compile_mo' => \$dont_compile_mo,
        'fix_po_from_tanker' => \$fix_po_from_tanker,
        'use_test_tanker' => \$use_test_tanker,
    );

    if ($help) {
        pod2usage({-message => ''});
        exit;
    } elsif (not defined $project) {
        Yandex::Tanker::_print_error_and_exit("'--project' is missing");
    } elsif (not defined $status) {
        Yandex::Tanker::_print_error_and_exit("'--status' is missing");
    } elsif (($status ne 'approved') and ($status ne 'unapproved')) {
        Yandex::Tanker::_print_error_and_exit("'--status' is incorrect");
    } elsif (not defined $opts_langs) {
        Yandex::Tanker::_print_error_and_exit("'--langs' is missing");
    }

    my @langs = split ',', $opts_langs;

    if (@langs < 1) {
        Yandex::Tanker::_print_error_and_exit("'--langs' is missing");
    }

    foreach my $lang (@langs) {
        if (not defined $LANG_CODES{$lang}) {
            Yandex::Tanker::_print_error_and_exit("'--langs' value '$lang' is incorrect");
        }
    }

    my $opts = {
        project => $project,
        status => $status,
        langs => \@langs,
        dont_delete_tmp_files => $dont_delete_tmp_files,
        dont_compile_mo => $dont_compile_mo,
        fix_po_from_tanker => $fix_po_from_tanker,
        use_test_tanker => $use_test_tanker,
        branch => $branch,
    };

    return $opts;
}

sub create_dir {
    my ($dir) = @_;

    if (!-d $dir) {
        mkdir($dir) or croak "Can't create dir '$dir': $!";
    }

    return '';
}

# main
sub main {

    my $opts = get_correct_opts();

    my $locale_dir = "./locale";
    if (!-d $locale_dir) {
        croak "Dir '$locale_dir' not found.";
    }

    my $tmp_dir = "./locale/tmp";
    system('rm -rf ./locale/tmp') and croak "Can't rm dir './locale/tmp': $!";
    create_dir($tmp_dir);

    my $tanker_url;
    if ($opts->{use_test_tanker}) {
        $tanker_url = $Yandex::Tanker::TEST_URL;
    } else {
        $tanker_url = $Yandex::Tanker::PROD_URL;
    }

    my $tanker = Yandex::Tanker->new({
        url     => $tanker_url,
        project => $opts->{project},
    });

    foreach my $lang (@{$opts->{langs}}) {
        my $po_content = $tanker->get_po_translation(
            language          => $lang,
            status            => $opts->{status},
            fix_po_content    => $opts->{fix_po_from_tanker},
            branch            => $opts->{branch},
        );

        write_file("./locale/tmp/$lang.po", $po_content);

        if (not $opts->{dont_compile_mo}) {
            my $lang_dir = "./locale/$LANG_CODES{$lang}";
            create_dir($lang_dir);
            create_dir("$lang_dir/LC_MESSAGES");

            my $cmd = "msgfmt $tmp_dir/$lang.po -o $locale_dir/$LANG_CODES{$lang}/LC_MESSAGES/$opts->{project}.mo";
            `$cmd`;
        }
    }

    if (not $opts->{dont_delete_tmp_files}) {
        system('rm -rf ./locale/tmp') and croak "Can't rm dir './locale/tmp': $!";
    }

}

main();
__END__
