#!/bin/sh -e
#
# This is a build script for all *.xml data used by Makefile (step 2)
# This is smart enough
#  * to skip po data for untranslated and
#  * to use fall back translation for zh-cn/zh-tw
#
rm -rf po2
cp -a po po2
# List of translation languges as arguments
LANGPO="$*"
# current debian-reference package verison in Debian
DVERSION=$(dpkg-parsechangelog -S Version)

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

# function to auto update zh-cn.po used for translation
gen_po_zh_CN() {
  if [ -f ${OPENCC} ]; then
    rm -f po2/zh-cn.po
    ${MSGCAT} --no-wrap po/zh-tw.po | ${OPENCC} -c ${DCC}/tw2sp.json -o po/zh-cn.po-opencc
    ${MSGCAT} -o po2/zh-cn.po --use-first po/zh-cn.po po/zh-cn.po-opencc
  fi
}

# functions to auto update zh-tw.po used for translation
gen_po_zh_TW() {
  if [ -f ${OPENCC} ]; then
    rm -f po2/zh-tw.po
    ${MSGCAT} --no-wrap po/zh-cn.po | ${OPENCC} -c ${DCC}/s2twp.json -o po/zh-tw.po-opencc
    ${MSGCAT} -o po2/zh-tw.po --use-first po/zh-tw.po po/zh-tw.po-opencc
  fi
}

# function to auto update pt.po used for translation
gen_po_pt() {
  rm -f po2/pt.po
  ${MSGCAT} -o po2/pt.po --use-first po/pt.po po/pt-br.po
}

# function to auto update pt-br.po used for translation
gen_po_pt_br() {
  rm -f po2/pt-br.po
  ${MSGCAT} -o po2/pt-br.po --use-first po/pt-br.po po/pt.po
}

# set up po4a2.cfg for po2
sed -e "s/@LANGPO@/${LANGPO}/" -e "s/@DVERSION@/${DVERSION}/" po4a2.cfg.in >po4a2.cfg
echo "I: create empty pot in po2/ with sure-to-be-older timestamp"
touch -t 200001010000.00 po2/debian-reference.pot
# fill some po files with auto-generated fall backs

if echo "${LANGPO}" | grep -q zh; then
  echo "I: update po2/zh-cn.po using opencc and po/zh-tw.po"
  gen_po_zh_CN &
  echo "I: update po2/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 po2/pt.po with po/pt-br.po as fall back"
  gen_po_pt &
  echo "I: update po2/pt-br.po with po/pt.po as fall back"
  gen_po_pt_br &
fi
# wait for all process to finish
echo "I: waiting for all updates to finish ..."
wait
echo "I: finished all updates"
echo "I: translate using updated po2/*.po data with debian-reference.en.xmlf"
echo "I: report of fuzzy translation is spurious and should be ignored"
# missing msgid/msgstr set on po files cause no problem since those are not translated.
po4a po4a2.cfg
