#! /usr/bin/perl

# This proggie takes a (possibly outdated) locale file as its (only)
# argument, and creates a new version, with `-work` appended. The thus
# created tile contains all keys of the master file, and is intended
# to, after manual editing, replace the outdated locale file.

# Written by Barf on 2005-12-10.
# reorganized by Stefan Seyfried 2016-01-03, following changes:
#  * use strict, use warnings to find errors easier
#  * make it work with the above pragmas
#  * tolerance against empty locales in english.locale

use warnings;
use strict;

my $masterfilename = "english.locale";

$#ARGV == 0 || die("Usage: create-locals-work file.locale.");

my $no_errors = 0;
my $last_was_ok = 1;
my $localefilename = $ARGV[0];
my $outfilename = $localefilename . "-work";

open(MASTER, $masterfilename) || die("Could not open master file $masterfilename");
open(LOCALE, $localefilename) || die("Could not open locale file $localefilename");
open(OUT, ">" . $outfilename) || die("Could not open output file $outfilename");

my %master;
my %locale;

my $line;
while ($line = <MASTER>) {
    # master hash
    chomp $line;
    $line =~ s/^\s+//; # strip whitespace from start of line
    my ($key, $text) = split /\s+/, $line, 2;
    $master{$key} = $text ? $text : "";
}
close(MASTER);

while ($line = <LOCALE>) {
    # locale hash
    chomp $line;
    $line =~ s/^\s+//;
    my ($key, $text) = split /\s+/, $line, 2;
    $locale{$key} = $text ? $text : "";
}
close(LOCALE);

foreach my $term (sort keys %master) {
    if (exists $locale{$term}) {
        print OUT $term." ".$locale{$term}."\n";
    } else {
        # not found
        $no_errors++;
        print OUT $term." TRANSLATE ".$master{$term}."\n";
    }
}

if ($no_errors == 0) {
    unlink($outfilename);
} else {
    print "There were ", $no_errors, " error(s) in ", $localefilename, ".\n";
}
