#!/usr/bin/perl

BEGIN { die "Do not run this as root" unless $>; }

use utf8;
use strict;
use warnings;
# use lib 'lib';
use Path::Tiny;
use AmuseWikiFarm::Utils::LexiconMigration;
use JSON;
use Getopt::Long;
use Pod::Usage;

=pod

=encoding utf8

=head1 NAME

amusewiki-upgrade-lexicon - Convert the legacy site_files/lexicon.json to po files.

=head1 SYNOPSIS

Usage: amusewiki-bootstrap-archive [ --help ] repo1, [ repo2, repo3 ]

Usually you would do:

 amusewiki-bootstrap-archive repo/*

from the application home.

If the target po file exist, it will be merged with the entries from
lexicon.json, which will take precendece (otherwise you shouldn't use
this script at all).

=cut

my ($help);

GetOptions(help => \$help) or die;

if ($help) {
    pod2usage;
    exit 2;
}

foreach my $dir (@ARGV) {
    my $path = path($dir)->absolute;
    next unless -d $path;

    my $lexicon = path($path, qw/site_files lexicon.json/);
    my $locales = path($path, qw/site_files locales/);
    if (-f $lexicon) {
        my $json = eval { JSON::from_json($lexicon->slurp_utf8) };
        if ($json) {
            if (my @generated = AmuseWikiFarm::Utils::LexiconMigration::convert($json, "$locales")) {
                print "Updated $dir lexicon\n";
            }
        }
        else {
            warn "Invalid json found\n";
        }
    }
}
