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

# This string can be anything; it is used as a standin for the actual
# string used to indent countries inside regions.
INDENTMARKER="[INDENT]"
# This is the actual indentation string. cdebconf supports escapes spaces
# in choices lists to preserve leading whitespace.
INDENT='\\  '

# Get the ordered list of countries from the iso_3166.tab, sorted
# according to the regionmap.
#
# We need to escape commas by preceding them with a backslash.
CHOICES=$(./countrylist $ISO3166TAB ./regionmap "$INDENTMARKER" | \
         sed 's/,/\\\\\\\\,/g' | \
         (read a; echo -n "$a"; while read b; do echo -n ", $b"; done; echo))

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

# 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] templates.tmp
../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

# (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
	# Munge the po file to have the indentmarker in its strings.
	perl -pe 'BEGIN { $marker=shift } s/^msg(id|str) "(.+)"/msg$1 "$marker$2"/' "$INDENTMARKER" \
		< $ISO3166TRANSLATIONS/$pofilename \
		> $ISO3166TRANSLATIONS/$pofilename.munged
	
	msgmerge -C debian/po/$pofilename \
                 -C $ISO3166TRANSLATIONS/$pofilename.munged \
                 /dev/null \
                 debian/pobuild/templates.pot \
		 > debian/pobuild/$pofilename
    # Else we just use what's translated
    else
	cp $pofile debian/pobuild/$pofilename
    fi
done

# and now we generate the templates file from all this
PODEBCONF_LIB=. po2debconf --podir debian/pobuild debian/templates.tmp >debian/templates

# Replace the indent marker with the actual indent.
perl -i -pe "s/\Q$INDENTMARKER\E/$INDENT/g" debian/templates
