#!/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"
# current debian-reference package verison in Debian
DVERSION=`dpkg-parsechangelog -S Version`

# 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
}

# Generate PO for pt (use pt-br as extra fallback data source)
gen_po_pt () {
        rm -f ${DPOTMP}/pt.po
        ${MSGCAT} -o ${DPOTMP}/pt.po --use-first ${DPO}/pt.po ${DPO}/pt-br.po
}

# Generate PO for pt-br (use pt as extra fallback data source)
gen_po_pt_br () {
        rm -f ${DPOTMP}/pt-br.po
        ${MSGCAT} -o ${DPOTMP}/pt-br.po --use-first ${DPO}/pt-br.po ${DPO}/pt.po
}



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
if echo ${LANGPO} | grep -q pt ; then
  echo "I: update po-tmp/pt.po with po/pt-br.po as fall back"
  gen_po_pt
  echo "I: update po-tmp/pt-br.po with po/pt.po as fall back"
  gen_po_pt_br
fi
