#!/usr/bin/perl

use JSON qw/decode_json/;
use Archive::Tar;
use POSIX 'strftime';

my $API_URL = "https://l10n.opensuse.org/api";
my $API_KEY = ""; # API key should be filled.
my @LANG_CODES = ( "ja" ); # Language code(s). For example: "ja" (Japanese)

my $cmdline = "curl -H \"Authorization: Token ${API_KEY}\" ${API_URL}";

my $outarc = Archive::Tar->new()
  or die "Error: unable to create archive: $!";

my $nextproj_url = "${API_URL}/projects/";
while (length($nextproj_url) > 0) {
  open(my $projlist, "curl -H \"Authorization: Token ${API_KEY}\" $nextproj_url 2> /dev/null |")
     or die "Error: Unable to retrieve project list: $!";
  my $projlist_json = decode_json(do { local $/; <$projlist> });

  foreach my $projitem (@{ $projlist_json->{'results'}}) {
    print STDERR "Found project: " . $projitem->{'name'} . "\n";

    my $nextcomp_url = "${API_URL}/projects/" . $projitem->{'slug'} . "/components/";
    while (length($nextcomp_url) > 0) {
      open(my $complist, "curl -H \"Authorization: Token ${API_KEY}\" $nextcomp_url 2> /dev/null |")
        or die "Error: Unable to retrieve component list for project: " . $projitem->{'name'} . ": $!";
      my $complist_json = decode_json(do { local $/; <$complist> });

      foreach my $compitem (@{ $complist_json->{'results'}}) {
        print STDERR "  Found component: " . $compitem->{'name'} . "\n";

        foreach my $langitem (@LANG_CODES) {
          open(my $transfile,
            "curl -s -S -H \"Authorization: Token ${API_KEY}\" " .
            "${API_URL}/translations/" .
            $projitem->{'slug'} . "/" . $compitem->{'slug'} . "/" . $langitem .
            "/file/ |")
            or die "Error: Unable to get translation file for project:" .
              $projitem->{'name'} . ", component=" . $compitem->{'name'} .
              ", language=" . $langitem . ": $!";

          $outarc->add_data($projitem->{'slug'} . "_" . $compitem->{'slug'} . "." .
            $langitem . ".po", do { local $/; <$transfile> }, FILE);

          close($transfile);
        }
      }

      close($complist);

      $nextcomp_url = $complist_json->{'next'};
    }
  }

  close($projlist);

  $nextproj_url = $projlist_json->{'next'};
}

print STDERR "Writing to archive..\n";

$outarc->write("weblatebackup." . strftime("%Y%m%d%H%M%S", localtime) .
  ".tar.gz", COMPRESS_GZIP);

print STDERR "done!\n";

