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

# Settings
bterm=/usr/bin/bterm
uni_font=/opt/drbl/lib/unifont.bgf
# Here we use another meta file instead of "dpkg-reconfigure console-data", since bterm will have a problem with argument more than one. i.e.
# bterm -l $LANG -f $uni_font "dpkg-reconfigure console-data" won't work.
#kbdconf="dpkg-reconfigure console-data"
kbdconf="/opt/drbl/sbin/ocs-dbn-kbdconf"

#
[ ! -e "$bterm" ] && exit 1
[ ! -e "$uni_font" ] && exit 1

# We need to know ocsroot and functions in ocs-functions
. /opt/drbl/sbin/drbl-conf-functions
. /opt/drbl/sbin/ocs-functions

ask_language_if_supported_with_bterm
[ -z "$ocs_lang" ] && ocs_lang=en

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

# Generate locale files.
# The outputs for localedef --list-archive are like:
# en_US.utf8
# zh_TW.utf8
# While we use en_US.UTF-8 or zh_TW.UTF-8 as the locale.
# Ex. zh_TW.UTF-8 -> zh_TW
locale_region="$(echo "$ocs_lang" | sed -e "s|\..*||g")"
if [ -z "$(localedef --list-archive | sed -e "s|\.utf8|.UTF-8|g" | grep -iw "$ocs_lang")" ]; then
  echo -n "Generating locale $ocs_lang by: localedef -f UTF-8 -i $locale_region $ocs_lang... "
  localedef -f UTF-8 -i $locale_region $ocs_lang
  echo "done!"
fi

export LANG="$ocs_lang"
if `locale_required_bterm_or_not "$locale_region"`; then
  export TERM=bterm
  set +e
  bterm -l $ocs_lang -f $uni_font $kbdconf
  set -e
else
  $kbdconf
fi
