#!/bin/sh
#
#
# chkconfig: 5 04 05
# description: This startup script sets locale from /proc/cmdline

WITHOUT_RC_COMPAT=1
KBDDIR=/etc/alterator/sysconfig/kbd
KBD_CONFIG=/etc/sysconfig/keyboard
XKB_CONFIG=/etc/X11/xinit/Xkbmap
CONFIGDIR=/etc/sysconfig/

i18n_conf="/etc/sysconfig/i18n"
langmap_conf="/etc/sysconfig/langmap"
rpm_conf="/etc/rpm/macros"

# Source function library.
. /etc/init.d/functions

RETVAL=0

start()
{
	in_locale=`grep -o 'lang=[^ ]*' /proc/cmdline`
	if [ $in_locale ] ; then
		in_locale=`echo $in_locale | cut -d = -f 2`
		echo "setting locale to $in_locale"
		#kbmap=`alterator-cmdline /sysconfig-base/kbd action list language $in_locale -k name | head -n 1`
		#alterator-cmdline /sysconfig-base/kbd action write language "$in_locale" layout "$kbmap"
		#alterator-cmdline /sysconfig-base/language action write lang "$in_locale"
		language="$in_locale"

		# Keyboard layout setup
		kbmap=`[ -d "$KBDDIR/$language" ] && find "$KBDDIR/$language" -name '*.xkb' | head -n 1 | sed 's,^.*/\(.*\)\.xkb$,\1,'`
		test "$language" = 'ru_RU' && kbmap='ctrl_shift_toggle'
		if test "$kbmap"
		then
            		path="$KBDDIR/$language/$kbmap"
	        	# update x11 keyboard mapping
        		install -Dpm644 "$path.xkb" "$XKB_CONFIG" && /usr/bin/setxkbmap -option "" && /usr/bin/setxkbmap `cat "$XKB_CONFIG"` >/dev/null
	        	# update console keyboard mapping
        		install -Dpm644 "$path.kbd" "$KBD_CONFIG" && /sbin/setsyskeytable >/dev/null
	      	else
        		rm -f "$KBD_CONFIG" "$XKB_CONFIG"
		fi

		# Default language setup
          	mkdir -p -- "${i18n_conf%/*}"
 	        mkdir -p -- "${langmap_conf%/*}"
        	mkdir -p -- "${rpm_conf%/*}"

          	firstlang="${language%%;*}"

          	printf 'LANG=%s.UTF-8\n' "$firstlang" > "$i18n_conf"

		if [ -z "${language##*;*}" ]; then
            		printf 'SUPPORTED=%s.UTF-8\n' "$language" >> "$i18n_conf"
            		printf '%s.UTF-8\n' "$language" > "$langmap_conf"
          	else
            		printf 'SUPPORTED=%s.UTF-8\n' "$firstlang" >> "$i18n_conf"
          	fi

          	sed 's,^%_install_langs[[:space:]].*,%_install_langs all,' -i "$rpm_conf"

		# Hack for tt locale
		if [ "${firstlang%.*}" = 'tt_RU' ]; then
			echo 'LANGUAGE=tt:ru' >>"$i18n_conf"
			subst 's/^SUPPORTED=.*$/SUPPORTED=tt_RU.UTF-8:ru_RU.UTF-8/' "$i18n_conf"
			printf '%s\n' "tt_RU.UTF-8:ru_RU.UTF-8" > "$langmap_conf"
		fi


		# Set language for indexhtml
		LANG="$firstlang.UTF-8" /usr/sbin/indexhtml-update
	fi
}

# See how we were called.
case "$1" in
	start)
		start
		;;
    stop|condstop|status)
        ;;
    restart|reload|condrestart|condreload)
        ;;
    *)
        msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
        RETVAL=1

esac

exit $RETVAL
