#!/bin/sh

# This script is used for translations using .po files.
# It updates .pot files after changes in the original English
# .xml files.
# The script 'merge_xml' should be run before this script!

if [ "$1" = "--help" ] ; then
    echo "Usage: $0"
    exit 0
fi

if [ -z "`which xml2pot 2>/dev/null`"  ] ; then
   echo "ERR: xml2pot not found, please install the poxml package"
   exit 1
fi

BUILDDIR="./build"
if [ -z "$PO_USEBUILD" ] ; then
    WORKDIR="./integrated"
    PODIR="./po"
else
    WORKDIR="$BUILDDIR/build.po"
    PODIR="$BUILDDIR/build.po"
fi
SOURCEDIR="$WORKDIR/en"
RET=0

[ -d $SOURCE ] || exit 1
mkdir -p $PODIR/pot

for XML in `find $SOURCEDIR -name "*.xml"` ; do
    echo "Creating new POT file for $XML"
    POT=$(basename $XML .xml).pot

    # Let's also set a proper POT-Creation-Date
    # The hack to set the POT creation date is no longer needed for poxml 3.5.0
    # But the authors of poxml also decided to set some nice KDE defaults we
    # don't want...
    xml2pot $XML | \
        sed "s/^.*Report-Msgid-Bugs-To:.*$/\"Report-Msgid-Bugs-To: debian-boot@lists.debian.org\\\n\"/" | \
        sed "s/^.*Language-Team:.*$/\"Language-Team: LANGUAGE <LL@li.org>\\\n\"/" | \
        sed "s/^.*POT-Creation-Date:.*$/\"POT-Creation-Date: $(date -u "+%F %R%z")\\\n\"/" \
        >$PODIR/pot/$POT.new
    RC=$?
    if [ $RC -ne 0 ] ; then
        RET=$RC
        echo "Error: error $RC while executing xml2pot"
    fi

    if [ ! -f $PODIR/pot/$POT ] ; then
        mv $PODIR/pot/$POT.new $PODIR/pot/$POT
    else
        if diff $PODIR/pot/$POT $PODIR/pot/$POT.new | grep "^[><]" | grep -qv "POT-Creation-Date: " ; then
            mv $PODIR/pot/$POT.new $PODIR/pot/$POT
        else
            # Revert changes if the only thing changed is the POT-Creation-Date
            rm $PODIR/pot/$POT.new
        fi
    fi
done

exit $RET
