#!/usr/bin/perl -w -T
# +=======================================================================+
# ||                                                                     ||
# ||                                                                     ||
# ||                                                                     ||
# ||                                                                     ||
# ||                                                                     ||
# ||                                                                     ||
# || (c) 2007 by Christian Kuelker                                       ||
# ||                                                                     ||
# || License GPLv2 or later                                              ||
# ||                                                                     ||
# +=======================================================================+
# Debian: liblocale-po-perl

use strict;

use Locale::PO;
use Carp;
use File::Basename;
use Getopt::Long;
#use lib '../../../common/src/lib'; 
use CipUX;

# +=======================================================================+
# || GLOBAL                                                              ||
# +=======================================================================+
delete @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};    # Make %ENV safer

my $source = 'C';
my $target = 'de';
my $destdir = $ENV{DESTDIR};
my $C = CipUX->new( { debug => 0 } );

# +=======================================================================+
# || CLI                                                                 ||
# +=======================================================================+

GetOptions(
    "source=s"     => \$source,       # C
    "target=s"     => \$target,       # de
    "destdir=s"    => \$destdir       # /tmp/xyz
    )or croak "Problems parsing command line!\n";

my $debug = 0;


$destdir = $C->l($destdir);

if($destdir ne ''){
  mkdir $destdir if !-d $destdir;
}

my $source_lang_path_code = $C->l($source);    # C
my $target_lang_path_code = $C->l($target);    # de

# source_template_files  = shift; # ../tpl/C/default/groupadmin/create.html

# +=======================================================================+
# ||                                                                     ||
# +=======================================================================+
my $filename = $target_lang_path_code . ".po";
my $po_href  = Locale::PO->load_file_ashash($filename);
foreach my $key ( sort keys %$po_href ) {
    print "KEY [$key] -> " . $$po_href{$key}->msgstr . "\n" if $debug;
    my $string = $$po_href{$key};
    $string =~ s/\s+//;
    if ( not defined($string) or $string eq "" ) {
        $$po_href{$key} = $key;
        print "WARNING: untranslated string [$key] in [$filename]!\n";
    }
}

# +=======================================================================+
# ||                                                                     ||
# +=======================================================================+
foreach my $filename (@ARGV) {
    print "parsing file $filename ...\n";
    open my $in, '<', $filename
      or croak "Can not open file [$filename] for reading!\n";
    my $data = do { local $/; <$in> };
    my $outdata = $data;
    while ( $data =~ m#<cat>(.*?)</cat>#sgmx ) {
        my $orig = $1;
        my $str  = $orig;
        $str =~ s/\n/\\n/gsmx;
        $str =~ s/\s+/ /gsmx;
        $str =~ s/\A\s*//gsmx;    # replace leading space
        $str =~ s/\s*\Z//gsmx;    # replace trailing space
        $str =~ s/^\s*//gsmx;
        $str =~ s/\s*$//gsmx;
        $str =~ s/"/\\"/gsmx;     # escape "
        $str =~ s/'/\\'/gsmx;     # escape '

        #	    $str =~ s/\s\s/\s/sgmx;
        $str = '"' . $str . '"';
        print "Y [$str][$$po_href{$str}] Y\n" if $debug;
        if ( defined( $$po_href{$str} ) ) {
            my $trans = $$po_href{$str}->msgstr;
            $trans = $$po_href{$str}->dequote($trans);
            print "X [$str][$trans] X\n"  if $debug;
            if ( defined($trans) ) {
                print "HIT [$orig] AS KEY [$str]\n" if $debug;
                print "REPLACE [$trans]\n" if $debug;

                #print "OUTDATA: [$outdata] OUTDATA\n";
                $outdata =~ m#<cat>(.*?)</cat>#sgmx;
                $orig    =~ s/\[/\\[/g; # [ -> \[
                $orig    =~ s/\]/\\]/g; # ] -> \]
                $orig    =~ s/\(/\\(/g; # ( -> \(
                $orig    =~ s/\)/\\)/g; # ) -> \)
                $trans   =~ s/\\n/\n/g;
                $outdata =~ s#<cat>$orig</cat>#$trans#sgm;
            }
            else {
                print "NOREPLACE\n";

                #$outdata =~ s#<cat>$orig</cat>#$orig#sgmx;
            }
        }
    }
    close $in;
    print "[$outdata]\n" if $debug;

    # my $target_lang_path_code = shift; # de
    # my $source_lang_path_code = shift; # C

    my $out_filename = $filename;
    $out_filename =~ s#/$source_lang_path_code/#/$target_lang_path_code/#g;
    $out_filename =~s#^../## if defined $ENV{DESTDIR};
    $out_filename = $destdir."/".$out_filename;
    $out_filename =~s#^//#/# if defined $ENV{DESTDIR};
    print "in  filename [$filename]\n";
    print "out filename [$out_filename]\n";
    print "destdir      [$destdir]\n"if defined $ENV{DESTDIR};
    if ( $out_filename ne $filename ) {
        if ( $out_filename =~ m#/$target_lang_path_code/# ) {
            # ok we can write it:
            my $dirname = $C->l(dirname($out_filename));
            system("mkdir -p $dirname") if !-d $dirname;
            if ( -d $dirname ) {
	        $out_filename = $C->l($out_filename);
                open my $out, ">", $out_filename;
                print $out $outdata;
                close $out;
            }
            else {
                error("directory $dirname do not exist!");
            }
        }
        else {
            error("wrong calculated target path! [$out_filename]");
        }
    }
    else {
        error("source and target are the same! [$out_filename]");
    }
}
exit(0);

sub error {
    my $msg = shift;
    chomp($msg);
    print "=" x 76 . "\n";
    print "ERROR: $msg \n";
    print "=" x 76 . "\n";
    exit(1);

}
