#!/bin/sh

usage()
{
    echo "This script updates the ooo-build-<lang>.po files"
    echo
    echo "Usage: ${0##*/} [--prefer-external] ooo_build_po_dir external_po_dir"
    echo
    echo "Parameters:"
    echo
    echo "	ooo_build_po_dir	path to the ooo-build/po direcotry"
    echo "	external_po_dir		directory with extrnal translations that"
    echo "				will be mergen into the ooo-build PO files"
    echo "	--prefer-external	use this option to prefer the translated"
    echo "				strings from the external PO files over"
    echo " 				any older ooo-build translation"
}

msgcat_options="--use-first"

if test "$1" = "--help" -o $# -lt 2 ; then
    usage
    exit 0;
fi

if test "$1" = "--prefer-external" ; then
    prefer_external=yes
    shift
else
    prefer_external=no
fi

ooo_build_po_dir="$1"
external_po_dir="$2"

if test ! -d "$ooo_build_po_dir" ; then
    echo "Error: Is not a direcotry: $ooo_build_po_dir"
    exit 1;
fi

if test ! -d "$external_po_dir" ; then
    echo "Error: Is not a direcotry: $external_po_dir"
    exit 1;
fi

for external_po in `find $external_po_dir -name "ooo-build*.po"` ; do
    # FIXME: openSUSE translation framework produces ooo-build.<lang>.po filenames instead of ooo-build-<lang>.po
    po_filename=`basename $external_po | sed -e "s|ooo-build\.|ooo-build-|" -e "s|_|-|g" `
    # FIXME: the en-US localization is useles
    test $po_filename = "ooo-build-en-US.po" && continue;
    # merge or add the PO file
    if test -f "$ooo_build_po_dir/$po_filename" ; then
	echo "Merging $po_filename..."
	po_tmp=`mktemp /tmp/ooo-update-po.XXXXXX`
	if test "$prefer_external" = "yes" ; then
	    msgcat $msgcat_options "$external_po" "$ooo_build_po_dir/$po_filename" >$po_tmp
	else
	    msgcat $msgcat_options "$ooo_build_po_dir/$po_filename" "$external_po" >$po_tmp
	fi
	# copy the updated file only when succeded
	if test "$?" = "0" ; then
	    mv $po_tmp "$ooo_build_po_dir/$po_filename"
	    chmod 644 "$ooo_build_po_dir/$po_filename"
	else
	    echo "Warning: $po_filename was not updated"
	fi
    else
	echo "Adding $po_filename..."
	cp "$external_po" "$ooo_build_po_dir/$po_filename"
    fi
done
