#!/bin/bash

# Copyright Jean-Philippe Guillemin <jp.guillemin@free.fr>. This program is free software;
# you can redistribute it and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version. Please take a look at http://www.gnu.org/copyleft/gpl.htm

# This script :
# - probes for available locales
# - ask the user for his choice
# - configure /etc/profile.d/lang.sh

# Version 1.0 - 01/09/2005
# Version 1.1 - 01/09/2005
#  * Added Xdialog support
#  * added icon support
# Version 1.2 - 22/10/2005
#  * Improved/secured tempdir management
# Version 1.3 - 06/04/2006
#  * Delete temp file


# Take a look at "Xdialog" and use it instead of "dialog" in case X is running
if [[ "$DISPLAY" && "$(which Xdialog 2>&1 | grep -v "which: no")" ]]; then
	dialog="Xdialog --screen-center --icon localeconfig"
	timeout="--timeout 2"
else
	dialog="dialog"
	timeout=""
fi

if [ "$(id -u)" == "0" ]; then
	langprofile="/etc/profile.d/lang.sh"
else
	langprofile="$HOME/.profile"
fi

touch $langprofile
if [ ! "$(grep "LANG=" $langprofile)" ] ; then 
	echo "# export the LANG variable (added by localeconfig)" >> $langprofile
	echo "export LANG=$LANG" >> $langprofile
fi

# Gettext internationalization
export TEXTDOMAIN="localeconfig"
export TEXTDOMAINDIR="/usr/share/locale"
. gettext.sh

# Path needs to be extended in case you're only half a root :)
export PATH="${PATH}:/usr/sbin:/sbin"

#################################################################
###########         LOCALE                        ###############
#################################################################



# probe for available locales and generate a menu

currentlocale="$LANG"

$dialog --title "$(eval_gettext 'Probing for locales')" --no-buttons --infobox "$(eval_gettext 'Please wait...')" 8 65 100000 &
pid=$!
list="$(locale -cva \
| sed -n '
/^locale:.*directory.*/{
s/^locale: \([^ ]*\) *directory.*$/"\1" /
P
N
N
s/.*title . \(.*\)$/"\1" /p'} \
| tr -d '\n' \
| sed 's/"nb_NO" //' )"

kill $pid

locale="$(eval $dialog \
--stdout \
--title \"$(eval_gettext 'System language configuration')\" \
--default-item \"${currentlocale}\" \
--cancel-label \"$(eval_gettext 'Exit')\" \
--menu \
\"\\n        $(eval_gettext 'Please select your prefered system language') \(locale\), \\n\
$(eval_gettext 'the current locale is :') $currentlocale\" 20 75 11 \
${list}
)"

if [ "$locale" ]; then
	if [ "$locale" == "$currentlocale" ]; then
		sed -i "s/^ *\(export LANG=\).*$/\1$locale/" $langprofile
		/bin/bash $langprofile
	else
		sed -i "s/^ *\(export LANG=\).*$/\1$locale/" $langprofile
		/bin/bash $langprofile
		$dialog $timeout --title "Changes at next login" --msgbox "\n $(eval_gettext 'You will need to login again for changes to take effect') $user\n" 8 65
	fi
fi
# end




