#!/usr/bin/perl -w

use warnings;
use strict;

# This script read the error-details.txt error details template, and prints to the
# std output the  contents of a possible .po file.
#
# This file consist of records like the following:
#
#  name: X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
#  detail: "SSL Certficate error: certificate issuer (CA) not known: %ssl_ca_name"
#  descr: "Unable to get issuer certificate"
#
# The records separated with an empty line.
# Comments starting with '#' supported.

my $File;
my $mode;

if (! ($File = shift @ARGV) ) {
    printf STDERR  "Usage: \n ".$0." error-detail-file\n\n";
    exit -1;
}

if (!open(IN, "<$File")) {
    printf STDERR "Can not open file %s\n", $File;
    exit -1;
}

my $lineNumber=0;
while(<IN>) {
    my($line) = $_;
    $lineNumber=$lineNumber+1;

    if ($line =~ /^\#.*/ ) {
#        print "Ignore comment: ".$line;
        next;
    }
    elsif ($line =~ /^\s*$/ ) {
#        print "Empty line!".$line;
        next;
    }
    my($rec) = "";
    my($lineOffset) = 0;
    do {
        $rec = $rec.$line;
        $line = <IN>;
        $lineOffset=$lineOffset+1;
    } while($line && $line !~ /^\s*$/);

    processRecord($rec, $lineNumber);
    $lineNumber= $lineNumber + $lineOffset;
}
exit(0);


sub processRecord
{
    my($rec, $lnumber) = @_;

#    print "Rec on $File:$lnumber:\n".$rec."--\n";
#    print "#: $File:$lnumber\n";
    my(@lines) = split /\n/, $rec;

    my($currentField) = "";
    my %currentRec;
    my $offset = 0;
    foreach (@lines) {
        my($l) = $_;
        if ($l =~ /^name:(.*)/) {
            $currentRec{"name"} = trim($1);
            $currentField = "name";
        }
        elsif ( $l =~ /^detail:(.*)/ ) {
            $currentRec{"detail"} = $1;
            $currentField = "detail";
        }
        elsif ($l =~ /^descr:(.*)/) {
            $currentRec{"descr"} = $1;
            $currentField = "descr";
        }
        elsif($l = ~ /^\s+(.*)/  && defined($currentRec{$currentField})) {
            $currentRec{$currentField}= $currentRec{$currentField}."\\n ".$1;
        }
    }
    print "#: $File+".$currentRec{"name"}.".detail:$lnumber\n";
    print    "msgid ".$currentRec{"detail"}."\n";
    print    "msgstr ".$currentRec{"detail"}."\n";
    print "\n";
    print "#: $File+".$currentRec{"name"}.".descr:$lnumber\n";
    print    "msgid ".$currentRec{"descr"}."\n";
    print    "msgstr ".$currentRec{"descr"}."\n";
    print "\n";
}

sub trim
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

