#!/usr/bin/perl -w
# --
# otrs.CreateNewTranslationFile - create new translation file
# Copyright (C) 2001-2006 OTRS GmbH, http://otrs.org/
# --
# $Id: otrs.CreateNewTranslationFile,v 1.16 2007/02/12 15:46:55 tr Exp $
# --
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# --

# use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);
use lib dirname($RealBin)."/Kernel/cpan-lib";

use strict;

use vars qw($VERSION %Opts);
$VERSION = '$Revision: 1.16 $';
$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

use Getopt::Std;
use Kernel::Config;
use Kernel::System::Log;
use Kernel::System::Main;
use Kernel::Language;

# get opts
getopt('olst',  \%Opts);

# print head
print "otrs.CreateNewTranslationFile <Revision $VERSION> - create new translation file\n";
print "Copyright (c) 2001-2006 OTRS GmbH, http://otrs.org/\n";
print "usage: otrs.CreateNewTranslationFile -l <Language> -t <dtl_files_or_directory>\n";

# common objects
my %CommonObject = ();
$CommonObject{ConfigObject} = Kernel::Config->new();
$CommonObject{LogObject} = Kernel::System::Log->new(
    LogPrefix => 'OTRS-CreateNewTranslationFile',
    %CommonObject,
);
$CommonObject{MainObject} = Kernel::System::Main->new(
    %CommonObject,
);

# check params
if (!$Opts{'l'}) {
    print "ERROR: -l <Language>!\n";
    exit 1;
}
else {
    $Opts{LanguageFile} = $CommonObject{ConfigObject}->Get('Home')."/Kernel/Language/$Opts{'l'}.pm";
    if (! -f $Opts{LanguageFile}) {
        print "ERROR: Not translation file: $Opts{LanguageFile}!\n";
        exit 1;
    }
}
if (!$Opts{'t'}) {
    $Opts{'t'} = $CommonObject{ConfigObject}->Get('Home').'/Kernel/Output/HTML/'.
        $CommonObject{ConfigObject}->Get('DefaultTheme').'/*.dtl';
    $Opts{LanguageOutFile} = $Opts{LanguageFile};
    print "INFO: Templates from $Opts{'t'}!\n";
    print "INFO: Output: $Opts{LanguageOutFile}!\n";
}
else {
    $Opts{'SubTranslation'} = 1;
    my $Out = $Opts{'t'};
    $Out =~ s/^.*\/(.+?)(\.dtl|)$/$1/;
    $Out =~ s/\*//g;
    $Opts{Out} = $Out;
    $Opts{LanguageOutFile} = $CommonObject{ConfigObject}->Get('Home')."/Kernel/Language/$Opts{'l'}_$Out.pm";
    print "INFO: Templates from $Opts{'t'}!\n";
    print "INFO: Output: $Opts{LanguageOutFile}!\n";
}

# common objects
$CommonObject{LanguageObject} = Kernel::Language->new(
    %CommonObject,
    UserLanguage => $Opts{'l'},
    TranslationFile => 1,
);

# open .dtl files and write new translation file
my $Data = '';
my %UsedWords = ();
my @List = glob("$Opts{t}");
foreach my $File (@List) {
    if (open (IN, "< $File")) {
        my $Content = '';
        while (my $Line = <IN>) {
            if ($Line !~ /^#/) {
                $Content .= $Line;
            }
        }
        close (IN);
        $File =~ s!^.*/(.+?)\.dtl!$1!;
        print "# Template: $File\n";
        $Data .= "\n        # Template: $File\n";
        # do dtl
        $Content =~ s{
            <dtl\sif.+?;\s\}>
        }
        {
            '';
        }egx;
        # do data
        $Content =~ s{
            \$(Env|Data|QData)({"(.+?)"}|{""}|{"(.+?)","(.+?)"})
        }
        {
            '';
        }egx;
        # do config
        $Content =~ s{
            \$Config({"(.+?)"}|{""})
        }
        {
            if (defined($2)) {
                $CommonObject{ConfigObject}->Get($2);
            }
            else {
                '';
            }
        }egx;
        # do translation
        $Content =~ s{
            \$Text({"(.+?)",.+?}|{"(.+?)"}|{""})
        }
        {
            my $Word;
            if (defined($2)) {
                $Word = $2;
            }
            if (defined($3)) {
                $Word = $3;
            }
            if ($Word && !$UsedWords{$Word}) {
                $UsedWords{$Word} = $CommonObject{LanguageObject}->Get($Word);
                my $Translation = $UsedWords{$Word} || '';
                if ($Translation eq $Word) {
                    $Translation = '';
                }
                $Translation =~ s/'/\\'/g;
                my $Key = $Word;
                $Key =~ s/'/\\'/g;
                if ($Key !~ /(a href|\$(Text|Quote)\{")/i) {
                    $Data .= "        '$Key' => '$Translation',\n";
                }
            }
            '';
        }egx;
    }
    else {
        die "Can't open $File: $!";
    }
}
# add misc words
print "# Misc\n";
$Data .= "        # Misc\n";
foreach my $Key (keys %{$CommonObject{LanguageObject}->{Translation}}) {
    if (!$UsedWords{$Key}) {
        my $Translation = $CommonObject{LanguageObject}->{Translation}->{$Key};
        $Translation =~ s/'/\\'/g;
        $Key =~ s/'/\\'/g;
        if ($Key !~ /(a href|\$(Text|Quote)\{")/i) {
            $Data .= "        '$Key' => '$Translation',\n";
        }
    }
}

# open old translation file
my %MetaData = ();
my $NewOut = '';
open (IN, "< $Opts{LanguageFile}") || die "Can't open: $Opts{LanguageFile}\n";
while (<IN>) {
    if (!$MetaData{DataPrinted}) {
        $NewOut .= $_;
    }
    if ($_ =~ /\$\$START\$\$/ && !$MetaData{DataPrinted}) {
        $MetaData{DataPrinted} = 1;
        $NewOut .= "    # Last translation file sync: ".scalar localtime()."\n\n";
        $NewOut .= "    # possible charsets\n".
            "    \$Self->{Charset} = [";
        foreach ($CommonObject{LanguageObject}->GetPossibleCharsets()) {
            $NewOut .= "'$_', ";
        }
        $NewOut .= "];\n".
            "    # date formats (\%A=WeekDay;\%B=LongMonth;\%T=Time;\%D=Day;\%M=Month;\%Y=Jear;)\n".
            "    \$Self->{DateFormat} = '$CommonObject{LanguageObject}->{DateFormat}';\n".
            "    \$Self->{DateFormatLong} = '$CommonObject{LanguageObject}->{DateFormatLong}';\n".
            "    \$Self->{DateFormatShort} = '$CommonObject{LanguageObject}->{DateFormatShort}';\n".
            "    \$Self->{DateInputFormat} = '$CommonObject{LanguageObject}->{DateInputFormat}';\n".
            "    \$Self->{DateInputFormatLong} = '$CommonObject{LanguageObject}->{DateInputFormatLong}';\n\n";
        if ($CommonObject{LanguageObject}->{TextDirection}) {
            $NewOut .= "    # TextDirection rtl or ltr\n";
            $NewOut .= "    \$Self->{TextDirection} = '$CommonObject{LanguageObject}->{TextDirection}';\n\n";

        }
        $NewOut .= "    \$Self->{Translation} = {";
        $NewOut .= $Data;
    }
    if ($_ =~ /\$\$STOP\$\$/) {
        $NewOut .= "    };\n".$_;
        $MetaData{DataPrinted} = 0;
    }
}
close (IN);

if ($Opts{'SubTranslation'}) {
    $NewOut = '';
    $NewOut .= "\n";
    $NewOut .= "package Kernel::Language::$Opts{'l'}_$Opts{Out};\n";
    $NewOut .= "\n";
    $NewOut .= "use strict;\n";
    $NewOut .= "\n";
    $NewOut .= "\n";
    $NewOut .= "sub Data {\n";
    $NewOut .= "    my \$Self = shift;\n";
    $NewOut .= "\n";
    $NewOut .= "    \$Self->{Translation} = { %{\$Self->{Translation}},\n";
    $NewOut .= $Data;
    $NewOut .= "\n";
    $NewOut .= "    };\n";
    $NewOut .= "}\n";
    $NewOut .= "1;\n";
}

if (-e $Opts{LanguageOutFile}) {
    print "INFO: Moving $Opts{LanguageOutFile} to $Opts{LanguageOutFile}.old\n";
    rename ($Opts{LanguageOutFile}, "$Opts{LanguageOutFile}.old") || die $!;
}

print "INFO: Writing $Opts{LanguageOutFile}\n";
open (OUT, "> $Opts{LanguageOutFile}") || die $!;
print OUT $NewOut;
close (OUT);

