#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# License: GPL

# Load DRBL setting and functions
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"

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

# Load keymap if it exists
[ -e /etc/ocs/ocs-live.conf ] && . /etc/ocs/ocs-live.conf

# Settings
mode=""

#
USAGE() {
    echo "$ocs - To configure the locales and keyboard layouts of live system"
    echo "Usage:"
    echo "To run $ocs:"
    echo "$ocs [OPTION]"
    echo
    echo "Options:"
    echo "-f, --force         Force to configure locales and keyboard layouts even they are done before"
    echo "-t, --fb-term TERM  Set the framebuffer term as TERM"
    echo
} # end of USAGE

####################
### Main program ###
####################

ocs_file="$0"
ocs=`basename $ocs_file`
#
while [ $# -gt 0 ]; do
 case "$1" in
   -f|--force) mode="force"; shift;;
   -t|--fb-term)
           # overwrite the fb_term in ocs-live.conf
           shift; 
           if [ -z "$(echo $1 |grep ^-.)" ]; then
             # skip the -xx option, in case 
             fb_term="$1"
             shift;
           fi
           [ -z "$fb_term" ] && USAGE && exit 1
           ;;
   -*)     echo "${0}: ${1}: invalid option" >&2
           USAGE >& 2
           exit 2 ;;
   *)      break ;;
 esac
done

if [ "$mode" = "force" ]; then
  # Modify the configuration file, clean the previou tag files, and reset related variables.
  perl -pi -e "s|^[[:space:]]*ocs_lang=.*|ocs_lang=|g" /etc/ocs/ocs-live.conf
  perl -pi -e "s|^[[:space:]]*live_keyboard_layouts=.*|live_keyboard_layouts=|g" /etc/ocs/ocs-live.conf
  rm -f /run/live/ocs-lang-kbd-conf /run/live/drbl-langchooser /run/live/drbl-kbdchooser
  ocs_lang=
  live_keyboard_layouts=
fi

if [ -z "$fb_term" ]; then
  get_fb_term
fi
[ "$fb_term" = "bterm" -a ! -e "$uni_font" ] && exit 1

export LANG="en_US.UTF-8"
gen_locale_if_not_found en_US en_US.UTF-8

#
export CURRENT_TTY="$(tty)"  # e.g. /dev/tty1, /dev/ttyS0...
# By default we will run "ocs-lang-kbd-conf" (same vc as $"$ocs_live_run_tty") in /dev/tty1 if ocs_live_run_tty is not specified. When "live-getty console=ttyS0,38400n81" is assigned, $ocs_live_run_tty is /dev/ttyS0. However, "ocs-lang-kbd-conf" might be run in runlevel 2 or systemd (e.g., called by /etc/rc2.d/S23start-ocs-live or /lib/systemd/system/start-ocs-live.service. In this case it's /dev/console) or after entering shell, it's the assigned console "$ocs_live_run_tty" or if it's not assigned, it's /dev/tty1.
# SUDO_TTY is assigned by "sudo -i SUDO_TTY="$(tty) ocs-live-run-menu" in ~user/.bash_profile.
# This is due to sudo >= 1.9.8p2-1 will new a pts (e.g., /dev/pts/0) instead of keeping the tty from SUDO_USER.
# Hence we use "sudo -i SUDO_TTY="$(tty)" ocs-live-run-menu" in .bash_profile. Then SUDO_TTY will be shown here.
if [ -n "$ocs_live_run_tty" ]; then
  # tty is specified, e.g. /dev/ttyS0. Check if it is the current tty
  if [ "$CURRENT_TTY" != "/dev/console" -a \
       "$CURRENT_TTY" != "$ocs_live_run_tty" -a \
       "$SUDO_TTY" != "/dev/console" -a \
       "$SUDO_TTY" != "$ocs_live_run_tty" ]; then
    echo "Not in /dev/console or \"$ocs_live_run_tty\", exiting $0..."
    exit 3
  fi
else
  # No tty is specified to run "ocs-lang-kbd-conf". Default to run only on /dev/console (runlevel 2) or /dev/tty1 (after entering shell).
  # If it's not in /dev/tty1 or /dev/console (during rc), just exit.
  if [ "$CURRENT_TTY" != "/dev/console" -a \
       "$CURRENT_TTY" != "/dev/tty1" -a \
       "$SUDO_TTY" != "/dev/console" -a \
       "$SUDO_TTY" != "/dev/tty1" ]; then
    echo "Not in /dev/console or /dev/tty1, exiting $0..."
    exit 3
  fi
fi

# ocs_live_keymap and live_keyboard_layouts are loaded from ocs-live.conf
if [ -z "$ocs_lang" -o -z "$live_keyboard_layouts" ]; then
  echo "Configuring language and keyboard..."
  # keymap not set in ocs-live.conf, use interactive dialog to set it.
  # Bterm/jfbterm/fbterm can only be used (it's better since Asian fonts can be shown) when:
  # (1) If bterm and uni fonts or fbterm/jfbterm are available
  # (2) If it's not in serial console
  # (3) frambebuffer device exists
  # (4) CPU arch is x86/x86-64 since jfbterm does not work on aarch64.
  if [ -n "$fb_term" ] && \
     [ -z "$(grep -E "console=.*ttyS.*" /proc/cmdline)" ] && \
     ([ -e /dev/fb/0 ] || [ -e /dev/fb0 ]) && \
     [ -n "$(LC_ALL=C uname -m | grep -iE "(x86_64|i[3-6]86)")" ]; then 
     case "$fb_term" in
       "bterm")
          export TERM=bterm
          set +e
          # bterm need full path command even it's in the PATH already.
          bterm -l $LANG -f $uni_font `command -v ocs-langkbdconf-bterm`
          set -e
          ;;
       "jfbterm")
          export TERM=jfbterm
          set +e
          jfbterm -q -e ocs-langkbdconf-bterm
          set -e
          ;;
       "fbterm")
          export TERM=fbterm
          . /etc/default/console-setup
          fontwidth="$(echo "$FONTSIZE" | cut -d'x' -f1)"
          fontheight="$(echo "$FONTSIZE" | cut -d'x' -f2)"
	  if [ -n "$fontwidth" -a -n "$fontheight" ]; then 
            font_opts="--font-width=$fontwidth --font-height=$fontheight"
	  fi
          set +e
          fbterm $font_opts -- ocs-langkbdconf-bterm
          set -e
          # Avoid fbterm issue
          disable_stdin_non_blocking_mode
          ;;
     esac
  else
    # ocs-langkbdconf-bterm does keyboard config and language config. Here we have do the same 2 jobs. Otherwise locales will be empty and a lot of warnings will be shown when ruuning commands.
    force_TERM_as_linux_if_necessary
    # (1) language
    [ -z "$ocs_lang" ] && ocs_lang=en_US.UTF-8
    # 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
    # (2) keyboard
    drbl-kbdchooser
  fi
fi
