#! /bin/sh

set -e

. /usr/share/debconf/confmodule

db_get debian-installer/locale
LOCALE="$RET"

# Set locale to C if it has not yet been set
# This can happen during e.g. s390 installs where localechooser is not run
[ "$LOCALE" ] || LOCALE="C"

if [ "$LOCALE" != "C" ] ; then
	db_get debian-installer/language
	LANGLIST="$RET"
fi

EXTRAS=""
if db_get localechooser/supported-locales ; then
	EXTRAS="$(echo "$RET" | sed 's/,//g')"
fi

LANGUAGE="${LOCALE%%_*}"

# Enable translations. 
if [ "$LOCALE" != "C" ] || [ "$EXTRAS" ]; then
	apt-install locales || true
fi

# Set global locale and language, and make sure the glibc locale is
# generated.
# TODO cjwatson 2006-02-19: remove any old LANG/LANGUAGE settings
DESTFILE="/target/etc/default/locale"
DESTFILE2="/target/etc/environment"
echo "LANG=\"$LOCALE\"" >> $DESTFILE
echo "LANG=\"$LOCALE\"" >> $DESTFILE2
# We set LANGUAGE only if the languagelist is a list of
# languages with alternatives. Otherwise, setting it is useless
if echo "$LANGLIST" | grep -q ":"; then
	echo "LANGUAGE=\"$LANGLIST\"" >> $DESTFILE
	echo "LANGUAGE=\"$LANGLIST\"" >> $DESTFILE2
fi

# For languages that have no chance to be displayed at the Linux console
# let's set root's environment with a non localized environment
ROOTPROFILE="/target/root/.profile"
# We must map the language to its "level" from languagelist
LANGUAGECODE=`echo $LOCALE|cut -f1 -d_`
# For language with multiple entries such as pt/pt_BR or zh_CN/zh_TW
# we don't really care about the entry we will match as the level will always 
# be the same 
LEVEL=`cat /usr/share/localechooser/languagelist |\
	cut -f 2-3 -d\; | \
	grep "$LANGUAGECODE" | \
	head -n 1 | \
	cut -f1 -d\;`
if [ "$LEVEL" = "3" ] || [ "$LEVEL" = "4" ] ; then
	echo "# Installed by Debian Installer:" >>$ROOTPROFILE
	echo "#  no localization for root because $LOCALE" >>$ROOTPROFILE
	echo "#  cannot be properly displayed at the Linux console" >>$ROOTPROFILE
	echo "LANG=C" >>$ROOTPROFILE
	echo "LANGUAGE=C" >>$ROOTPROFILE
fi

# If the locale isn't already valid, append it to locale.gen
if [ -x /target/usr/sbin/validlocale ] ; then 
	gen=""
	if log-output -t localechooser --pass-stdout \
	    chroot /target/ /usr/sbin/validlocale "$LOCALE" \
	    >> /target/etc/locale.gen; then
		: # Nothing to do
	else
		# New locale added to locale.gen, generate it
		gen=1
	fi
	for loc in $EXTRAS; do
		if [ "$loc" = "$LOCALE" ]; then
			continue
		fi
		if log-output -t localechooser --pass-stdout \
		    chroot /target/ /usr/sbin/validlocale "$loc" \
		    >> /target/etc/locale.gen; then
			: # Nothing to do
		else
			# New locale added to locale.gen, generate it
			gen=1
		fi
	done
	if [ "$gen" ]; then
		if [ -x /target/usr/sbin/locale-gen ] ; then 
			log-output -t localechooser --pass-stdout \
			    chroot /target /usr/sbin/locale-gen --keep-existing >/dev/null
		fi
	fi
fi
	
exit 0
