#!/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
#
# Translations location (relative to the build root directory)
ISO3166TRANSLATIONS=debian/iso-codes

templates_in=$1
templates_out=$2

# Create a temporary "pobuild" directory
rm -rf debian/pobuild >/dev/null 2>&1
mkdir debian/pobuild

# Create the appropriate POTFILES.in file there
cat >debian/pobuild/POTFILES.in <<EOF
[type: gettext/rfc822deb] $(basename $templates_in)
[encoding: UTF-8]
../regionmap
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

# process each existing file in debian/po
for pofile in debian/po/*.po ; do
	pofilename=$(basename $pofile)
	printf "$pofilename "
	# If the country names are translated, we need to merge
	# the translation with the templates translations
	if [ -f $ISO3166TRANSLATIONS/$pofilename ]; then
		# msgcat will properly handle different encodings
		msgcat --use-first $ISO3166TRANSLATIONS/$pofilename \
			debian/po/$pofilename \
			> debian/pobuild/$pofilename 2>/dev/null

		msgmerge -U debian/pobuild/$pofilename \
			debian/pobuild/templates.pot
	else
		# just use what's translated
		cp $pofile debian/pobuild/$pofilename
	fi
done
echo

# and now we generate the templates file from all this
po2debconf --podir debian/pobuild $templates_in >$templates_out
