#!/bin/bash
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL
# This program is used in Debian and run in bterm or jfbterm

#
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/opt/drbl/}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. $DRBL_SCRIPT_PATH/conf/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

#
get_fb_term
[ "$fb_term" = "bterm" -a ! -e "$uni_font" ] && exit 1

# Read the setting if exists
[ -e "/etc/drbl/drbl-live.conf" ] && . /etc/drbl/drbl-live.conf
if [ -z "$drbl_lang" ]; then
  if [ "$TERM" = "bterm" -o "$TERM" = "jfbterm" ] && ([ -e /dev/fb/0 ] || [ -e /dev/fb0 ]); then 
    TMP="$(mktemp /tmp/lang.XXXXXX)"
    drbl-langchooser $TMP
    drbl_lang="$(cat $TMP)"
    [ -f "$TMP" ] && rm -f $TMP
  fi
fi
[ -z "$drbl_lang" ] && drbl_lang=en_US.UTF-8

# put the language setting so that later program can reuse
if [ -z "$(grep -E "^[[:space:]]*drbl_lang=" /etc/drbl/drbl-live.conf 2>/dev/null)" ]; then
  # append it
  echo "drbl_lang=$drbl_lang" >> /etc/drbl/drbl-live.conf
else
  # modify it
  perl -pi -e "s|^[[:space:]]*drbl_lang=.*|drbl_lang=\"$drbl_lang\"|g" /etc/drbl/drbl-live.conf
fi

#
locale_region="$(echo "$drbl_lang" | sed -e "s|\..*||g")"
gen_locale_if_not_found $locale_region $drbl_lang

#
echo "Setting locale in /etc/default/locale... "
cat <<-LOCALE_END > /etc/default/locale
LC_ALL="${drbl_lang}"
LANG="${drbl_lang}"
LOCALE_END

echo "Setting locale in /etc/environment... "
cat <<-LOCALE_END > /etc/environment
LC_ALL="${drbl_lang}"
LANG="${drbl_lang}"
LOCALE_END

export LANG="$drbl_lang"
dpkg-reconfigure console-data
