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

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

# Load the options from config file
[ -e /etc/ocs/ocs-live.conf ] && . /etc/ocs/ocs-live.conf

# Set initial value if not set
[ -z "$ocs_live_run" ] && ocs_live_run="ocs-live-general"
[ -z "$ocs_live_keymap" ] && ocs_live_keymap="NONE"
[ -z "$ocs_live_batch" ] && ocs_live_batch="no"
[ -z "$ocs_lang" ] && ocs_lang="en_US.UTF-8"

#
if [ -z "$ocs_live_run" ]; then
  echo "No \$ocs_live_run was assigned (Either from /etc/ocs/ocs-live.conf or command kernel parameters). Skip Clonezilla-related action."
  exit 3
fi

# Get the live media mount point.
get_live_media_mnt_point

if [ -z "$LIVE_MEDIA" -o ! -d "/$LIVE_MEDIA" ]; then
  echo "$0 is run in Clonezilla Live!"
  echo "Program terminated!"
  exit 1
fi

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

use_bterm=""
# Ex. zh_TW.UTF-8 -> zh_TW
locale_region="$(echo "$ocs_lang" | sed -e "s|\..*||g")"
if `locale_required_bterm_or_not "$locale_region"` && \
   [ -n "$fb_term" ] && \
   ([ -e /dev/fb/0 ] || [ -e /dev/fb0 ]); then 
   use_bterm="yes"
else
   use_bterm="no"
fi

#
gen_locale_if_not_found $locale_region $ocs_lang

# export these variables so that they can be passed to $ocs_live_run in bterm
export LANG="$ocs_lang"
export CURRENT_TTY="$(tty)"  # e.g. /dev/tty1

# By default we will run $ocs_live_run in /dev/tty1 if ocs_live_run_tty is not specified.
if [ -n "$ocs_live_run_tty" ]; then
  # tty is specified. Check if it the current tty
  [ "$CURRENT_TTY" != "$ocs_live_run_tty" ] && exit 3
else
  # No tty is specified to run $ocs_live_run_tty. Default to run only on /dev/tty1 (no more ttyS0). If you want to use ttyS0, add live-getty and console=ttyS0,38400n81 in the boot parameter 
  # If it's not in /dev/tty1, just exit.
  [ "$CURRENT_TTY" != "/dev/tty1" ] && exit 3
fi

# Do not ask powerer/reboot/choose (-p) in $ocs_live_run (ocs-live-save/ocs-live-restore), just use "-p true" in $ocs_live_run (ocs-live-save/ocs-live-restore). Since it might be in bterm, and Debian live "Press Enter" message when poweroff/shutdown might be coverd by bterm and user will not have any idea what's happening after choose poweroff/reboot. We will ask it when bterm is done, i.e. in the end of this program.
if [ "$use_bterm" = "yes" ];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 `which $ocs_live_run`
       EXIT=$?
       set -e
       ;;
  "jfbterm")
       export TERM=jfbterm
       set +e
       jfbterm -q -e $ocs_live_run
       EXIT=$?
       set -e
       ;;
  esac
else
  $ocs_live_run
fi

# now it's not in bterm, only text console. Use English. 
ask_and_load_lang_set en_US.UTF-8
run_post_cmd_when_clonezilla_live_end
