#!/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 --wrap --left --screen-center"
else
	dialog="dialog"
fi

# Translations only work with utf8 locales
if [ ! `echo $LANG | grep -i utf` ]; then
	LANG=en_US
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="$(cat /etc/profile.d/lang.sh \
  | grep -E "^[[:space:]]*export LANG=" \
  | sed -e "s/^[ ]*export LANG=\(.*\)$/\1/")"

$dialog --timeout 5 --icon "localeconfig" --title "$(eval_gettext 'Probing')" --msgbox "$(eval_gettext 'Probing locales and building a list for you ...')" 0 0 &


list="$(locale -cva \
| grep -E "^locale|.*title \| " \
| sed '
/^locale:.*directory.*/{
s/^locale: \([^ ]*\) *directory.*$/\1/
N
s/^\(.*\) *\n *title . \(.*\)$/"\1" "\2 " \\/'})"



locale="$(eval $dialog \
--stdout \
--title \"$(eval_gettext 'System language configuration')\" \
--default-item \"${currentlocale}\" \
--cancel-label \"$(eval_gettext 'Exit')\" \
--icon \"localeconfig\" \
--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
  sed -i "s/^ *\(export LANG=\).*$/\1$locale/" /etc/profile.d/lang.sh
  /bin/bash /etc/profile.d/lang.sh

fi

# end




