#!/bin/sh -e
#
# This is a build script for all *.xml data used by Makefile
# This is smart enough
#  * to skip po data for untranslated and
#  * to use fall back translation for zh-cn/zh-tw
#
# List of translation languges as arguments
LANGPO="$*"
# Directory holding po data based on debian-reference.en.xmlt (persistent)
DPO="po"
# Directory holding po data applied to debian-reference.en.xml (temporary)
DPOTMP="po-tmp"
DBIN="bin"
# data directory for opencc
DCC="/usr/share/opencc"
# The threshold should be 80 if translation is completed.
MSGCAT="/usr/bin/msgcat"
# command to auto-translate between zh-cn <-> zh-tw
OPENCC="/usr/bin/opencc"

# Generate PO for zh-cn (use zh-tw as extra fallback data source with help of opencc)
gen_po_zh_CN () {
    if [ -f ${OPENCC} ] ; then
        rm -f ${DPOTMP}/zh-cn.po
        ${MSGCAT} --no-wrap ${DPO}/zh-tw.po | ${OPENCC} -c ${DCC}/tw2sp.json -o ${DPO}/zh-cn.po-opencc
        ${MSGCAT} -o ${DPOTMP}/zh-cn.po --use-first ${DPO}/zh-cn.po ${DPO}/zh-cn.po-opencc
    fi
}

# Generate PO for zh-tw (use zh-cn as extra fallback data source with help of opencc)
gen_po_zh_TW () {
    if [ -f ${OPENCC} ] ; then
        rm -f ${DPOTMP}/zh-tw.po
        ${MSGCAT} --no-wrap ${DPO}/zh-cn.po | ${OPENCC} -c ${DCC}/s2twp.json -o ${DPO}/zh-tw.po-opencc
        ${MSGCAT} -o ${DPOTMP}/zh-tw.po --use-first ${DPO}/zh-tw.po ${DPO}/zh-tw.po-opencc
    fi
}


echo "I: build English source"
make debian-reference.en.xml
echo "I: build English source (less non-translating strings to reduce po size)"
make debian-reference.en.xmlt
# since po/debian-reference.pot is commited to git repo, no need to do this any more.
#touch -t 200001010000.00 po/debian-reference.pot
# set up po4a.cfg for po
sed -e "s/@LANGPO@/${LANGPO}/" po4a.cfg.in > po4a.cfg
echo "I: update po/*.po based on debian-reference.en.xmlt"
po4a --msgmerge-opt --verbose -v --no-translations po4a.cfg
echo "I: create po-tmp/* for debian-reference.en.xml"
rm -rf po-tmp
cp -r po po-tmp
if echo ${LANGPO} | grep -q zh ; then
  echo "I: update po-tmp/zh-cn.po using opencc and po/zh-tw.po"
  gen_po_zh_CN
  echo "I: update po-tmp/zh-tw.po using opencc and po/zh-cn.po"
  gen_po_zh_TW
fi
# set up po4a-tmp.cfg for po-tmp
sed -e "s/@LANGPO@/${LANGPO}/" po4a-tmp.cfg.in > po4a-tmp.cfg
echo "I: create empty pot in po-tmp/ with sure-to-be-older timestamp"
touch -t 200001010000.00 po-tmp/debian-reference.pot
echo "I: update po-tmp/*.po data and build all translations based on debian-reference.en.xml"
po4a -v po4a-tmp.cfg
#rm -rf po-tmp


