#!/bin/sh

set -e

#
# Script for generating a debconf templates file from both files
# in debian/po/*.po and country names translations from the
# iso-codes package
#
# Some variables
ISOQUERY=/usr/bin/isoquery
# Translations location (relative to the build root directory)
ISO639TRANSLATIONS=debian/iso-codes
#
# This file will have all wanted languages, one ISO-639-2 code per line
LANGUAGELIST=debian/languages

# For each supported language, get the language name from ISO 639-2 list
(for lang in `cat debian/languages | grep -v "^#"` ; do
  $ISOQUERY --iso=639-2 $lang | cut -f4
done) | \
(read a; echo -n "$a"; while read b; do echo -n ", $b"; done; echo) \
>debian/languagelist

CHOICES=`cat debian/languagelist`
rm debian/languagelist || true

# Now put this list as the choices in the templates
# and defined this field as translatable (__Choices hack)
cat debian/geneweb.templates.master | \
    perl -pe 's/\@LANGUAGELIST\@/'"$CHOICES"'/g' | \
    sed '/Choices:.*English/s/Choices/__Choices/g' \
    >debian/geneweb.templates.tmp

# Create a temporary "pobuild" directory
rm -rf debian/pobuild || true
mkdir debian/pobuild

# Create the appropriate POTFILES.in file there
cat >debian/pobuild/POTFILES.in <<EOF
[type: gettext/rfc822deb] geneweb.templates.tmp
EOF

# Create the appropriate output file also
cat >debian/pobuild/output <<EOF
2   utf8
EOF

# Run debconf-updatepo on this directory
# -->this will create pobuild/templates.pot
debconf-updatepo --podir debian/pobuild

# The following takes place for each language
# (each existing file in debian/po
echo "Compiling in ISO-639-2 languages translations:"
for pofile in debian/po/*.po ; do
    pofilename=`basename $pofile`
    echo -n "$pofilename "|sed 's/\.po//g'
    echo -n "..."
    # If the language names are translated, we need to merge
    # the translation with the templates translations
    if [ -f $ISO639TRANSLATIONS/$pofilename ]
    then
        # the temporary po files will be UTF-8 encoded
	cat debian/pobuild/templates.pot | \
	    sed '/^\"Content-Type/s/CHARSET/UTF-8/' \
	    > debian/pobuild/$pofilename.temp

	pocharset=`grep -ai charset $pofile|cut -f2 -d=| sed 's/\\\\n\\"//g'`
	cat $pofile | \
            iconv --from $pocharset --to utf-8 | \
	    sed "s/$pocharset/UTF-8/g" \
	    > debian/pobuild/$pofilename.ori

	cp debian/pobuild/$pofilename.temp debian/pobuild/templates.pot.temp

	msgmerge -C debian/pobuild/$pofilename.ori \
                 -C $ISO639TRANSLATIONS/$pofilename \
                 debian/pobuild/$pofilename.temp \
                 debian/pobuild/templates.pot.temp \
		 > debian/pobuild/$pofilename 2>/dev/null
    # Else we just use what's translated
    else
	cp $pofile debian/pobuild/$pofilename
    fi
    echo " done."
done

echo -n "Generating templates file with po2debconf..."
# and now we generate the templates file from all this
po2debconf -e utf8 --podir debian/pobuild debian/geneweb.templates.tmp >debian/geneweb.templates
echo "done."
