#!/bin/sh

usage()
{
    echo "This script converts one PO file to one SDF (GSI) file format"
    echo
    echo "Usage:" ${0##*/} lang sdf_template po_file sdf_file
    echo
    echo "Arguments:"
    echo
    echo "	lang:	      language id, e.g \"de\""
    echo "	sdf_template: original sdf file that has been used to generate"
    echo "	              the .pot file"
    echo "	po_file:      input .po file"
    echo "	sdf_file:     output .sdf file"
    echo
    echo "IMPORTANT: this is only a temporary solution until"
    echo "           http://bugs.locamotion.org/show_bug.cgi?id=487"
    echo "           is fixed"
}

if test -z "$1"  -o  "$1" = "--help" ; then
    usage && exit 1;
fi

lang=$1
sdf_template=$2
po_in=$3
sdf_out=$4

if ! which po2oo >/dev/null 2>&1 ; then
    echo "Error: po2oo tool is not available!"
    echo "       You need to install translate-toolkit, see" ; \
    echo "       http://translate.sourceforge.net/wiki/start" ; \
    echo "       The package for openSUSE it named python-translate-toolkit" ; \
    echo "       and can be found at" ; \
    echo "       http://download.opensuse.org/repositories/OpenOffice.org:/EXTRAS/" ; \
    exit 1;
fi

# Crazy hack until http://bugs.locamotion.org/show_bug.cgi?id=487" is fixed"

# translate-toolkit-1.1.1 is not able to convert it in
# the--multifile=onefile format, so we need to split the .po file
# to get the --multifile=toplevel format
#
# We get the split .pot file and copy the .po file accordingly to get the same
# structure. We get a lot warnings but it works.

# get the split pot file
pot_topdir=`mktemp -d /tmp/po2sdf-pot.XXXXXX`
oo2po -P --multifile=toplevel $sdf_template $pot_topdir

# "split" the po file accordingly
po_in_topdir=`mktemp -d /tmp/po2sdf-po.XXXXXX`
for pot in `ls $pot_topdir` ; do
    pot_name=${pot%.pot}
    # we get many warnings later when the full .po file is just copied
    # it might be better to really split it but...
    cp $po_in $po_in_topdir/$pot_name.po
done
rm -rf $pot_topdir

# finally, generate the sdf file
# there are many error messages because of the copied .po files but it somewhat works
sdf_unsorted=`mktemp /tmp/po2sdf-sdf.XXXXXX`
po2oo --nofuzzy --multifile=toplevel  -l $lang -t $sdf_template -i $po_in_topdir -o $sdf_unsorted 2>/dev/null

if test ! -s $sdf_unsorted ; then
    echo "Error: The generated SDF file is empty!"
    echo "Please, edit the ${0##*/} script and enable error messages in the po2oo command."
    err=1;
else
    # DOS end of lines can't be commited into libreoffice git
    if which dos2unix >/dev/null 2>&1 ; then
        dos2unix $sdf_unsorted
    else
        echo "Warning: You might want to install dos2unix tool to get correct .sdf files"
    fi
    sort $sdf_unsorted >$sdf_out
    err=0
fi

rm -rf $po_in_topdir
rm -f $sdf_unsorted

exit $err
