#!/usr/bin/perl

use strict;
use JSON;
use Getopt::Long;
use Encode::Locale qw/decode_argv/;
my ( $portal, $modify, $help, $delete, $reorder );
my $json =
  JSON->new->utf8->pretty()->canonical()->space_before(0)->space_after(0);

decode_argv();
GetOptions(
    "portal|p"  => \$portal,
    "modify|m"  => \$modify,
    "delete|d"  => \$delete,
    "reorder|r" => \$reorder,
    "help|h"    => \$help,
);
usage() if $help or ( !@ARGV and !$reorder );
my $key    = shift @ARGV;
my $enText = shift @ARGV;
my $frText = shift(@ARGV) || $enText;

# Check args
usage() if $delete and $modify;
if ($key) {
    usage() if $reorder;
    if ($delete) {
        usage() if $enText;
    }
    else {
        usage() unless $enText;
    }
}
else {
    usage() unless $reorder;
}

# Main
my $wdir =
    'lemonldap-ng-'
  . ( $portal ? "portal" : "manager" )
  . '/site/htdocs/static/languages';
opendir D, $wdir or die "unable to open $wdir";
my @langs = grep { /\.json$/ } readdir D;
closedir D;
for my $lang (@langs) {
    my ( $file, $content );
    {
        local $/ = undef;
        open $file, "$wdir/$lang" or die $!;
        binmode $file;
        $content = <$file>;
        close $file;
    }
    my $jsonObj = $json->decode($content);
    if ($key) {
        if ( $jsonObj->{$key} xor( $delete or $modify ) ) {
            print STDERR ( $jsonObj->{$key}
                ? "key already exists\n"
                : "key doesn't exit\n" );
            usage();
        }
        if ($delete) {
            delete $jsonObj->{$key};
        }
        else {
            my $text = ($lang eq 'fr.json' ? $frText : $enText);
            if ($text =~ /^\$(.*)/) {
                die "\$$1 not found" unless $jsonObj->{$1};
                $jsonObj->{$key} = $jsonObj->{$1};
            } else {
                $jsonObj->{$key} = $text;
            }
        }
    }
    $content = $json->encode($jsonObj);
    $content =~ s/\n\s+/\n/sg;
    $content =~ s/\n*$//s;
    open $file, '>', "$wdir/$lang" or die $!;
    binmode $file;
    print $file $content;
    close $file;
}

## usage
sub usage {
    print STDERR <<EOT;
Usage:
$0 <option> key enText <frText>
$0 <option> key '\$otherkey'

Options:
  --portal  -p: add entry in portal translation instead of manager
  --modify  -m: modify an existing entry
  --delete  -d: delete an existing key
  --reorder -r: reorder files
  --help   -h: display this
EOT
    exit( $help ? 0 : 1 );
}
