#! /usr/bin/perl -w
#####
#for-proofread old.pot new.pot > file_for_proofread.po
#
#Create a .po file with strings for proofreading. It will not contain
#strings that are both in old.pot and new.pot as msgids.
#####
# Author: Jan Holesovsky <kendy@suse.cz>

use File::Temp qw/ tempfile tempdir /;

sub usage()
{
    # Isn't the following too anti-perl? :-)
    my $message = `sed -e '/^#####/,/^#####/!d' -e 's/^#*//' $0`;
    die "$message";
}

# Let's get the params
usage() unless $#ARGV == 1;
($old_fname, $new_fname) = @ARGV;

# Create a temporary file
($TMP, $tmp_fname) = tempfile( "/tmp/proofread_XXXXXX", SUFFIX => '.po');

# Create temporary .po file with the opd translations
open (OLD, '<', $old_fname) or die ("Cannot open old .pot file.\n");

my $copy_msgid = 0;
my $buffer = "";
while (<OLD>)
{
    if (/^msgid/)
    {
	$copy_msgid = 1;
	$buffer = "";
    }
    if (/^msgstr/)
    {
	$copy_msgid = 0;
	print $TMP "$buffer\n";
    }

    if ($copy_msgid == 1)
    {
	print $TMP $_;

	s/^msgid/msgstr/;
	$buffer .= $_;
    }
}

close (OLD);
close ($TMP);

# Inject it to the new .pot
open (NEW, "msgmerge $tmp_fname $new_fname -o - |");

my $fuzzy        = 0;
my $empty_msgstr = 0;
$copy_msgid      = 0;
$buffer          = "";
$buffer_comment  = "";
$comment         = "";
while (<NEW>)
{
    $fuzzy = 1 if (/^#,/ && /fuzzy/);
    
    $buffer_comment .= $_ if (/^#/);
    
    # We write the msgid in two cases:
    # case 1: the msgstr is empty
    if ($buffer ne "" && $fuzzy != 1 && $empty_msgstr == 1 && /^[^\"]/)
    {
	print "$comment$buffer"."msgstr \"\"\n\n";
    }
    $empty_msgstr = 0;

    if (/^msgid/)
    {
	$comment = $buffer_comment;
	$buffer_comment = "";

	$copy_msgid = 1;
	$buffer     = "";
    }
    if (/^msgstr/)
    {
	# case 2: the message is fuzzy
	if ($fuzzy == 1)
	{
	    print "$comment$buffer"."msgstr \"\"\n\n";
	    $fuzzy = 0;
	}
	$copy_msgid = 0;
	
	$empty_msgstr = 1 if /^msgstr +""/;
    }
    
    $buffer .= $_ if ($copy_msgid == 1);
}

# let's not forget the last message
if ($buffer ne "" && $fuzzy != 1 && $empty_msgstr == 1)
{
    print "$comment$buffer"."msgstr \"\"\n\n";
}

close (NEW);

unlink ($tmp_fname);
