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

# We need to know ocsroot.
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 the options from config file
[ -e /etc/ocs/ocs-live.conf ] && . /etc/ocs/ocs-live.conf

ask_and_load_lang_set $ocs_lang

# check DIA
check_DIA_set_ESC $DIA

##############
#### main ####

TMP="$(mktemp /tmp/ocs_final_act.XXXXXX)"

if mountpoint $ocsroot &>/dev/null; then
  rerun2_ocs_with_repo_mounted_1="rerun2"
  rerun2_ocs_with_repo_mounted_2="$(rep_whspc_w_udrsc "$msg_run_clonezilla_live_again_but_keep_mounted_repository")"
fi

final_action_flag=1
while [ "$final_action_flag" -ne 0 ]; do
  $DIA --default-item "cmd" --nocancel --backtitle "Free Software Labs, NCHC, Taiwan" --title  \
  "Choose mode" --menu "$msg_clone_finished_choose_to:" \
  0 0 0 \
  poweroff "$msg_poweroff" \
  reboot "$msg_reboot" \
  cmd "$msg_enter_cml" \
  rerun1 "$msg_run_clonezilla_live_again" \
  $rerun2_ocs_with_repo_mounted_1 $rerun2_ocs_with_repo_mounted_2 \
  2> $TMP
  final_action="$(cat $TMP)"
  if [ -z "$lang" ]; then
    final_action_flag=1
  else
    final_action_flag=0
  fi
done
[ -f "$TMP" ] && rm -f $TMP

case "$final_action" in
  poweroff) unmount_mounted_fs_before_ocs_live_reboot
     echo -n 'Will poweroff... '
     countdown 5
     poweroff $HALT_REBOOT_OPT ;;
  reboot) unmount_mounted_fs_before_ocs_live_reboot
     echo -n 'Will reboot... '
     countdown 5
     reboot $HALT_REBOOT_OPT ;;
  rerun*) # umount the clonezilla home dir
     if [ "$final_action" = "rerun1" ]; then
       echo "Completely start over, so umounting $ocsroot..."
       unmount_mounted_fs_before_ocs_live_reboot
     else
       echo "Keep the mounted image repository $ocsroot..."
     fi
     echo -n 'Run Clonezilla live again... '
     # since we are not in login shell, it's useless to use "exit" or "logout" to force logout bash. Use kill to terminate the login shell in tty1. The clonezilla live main menu will be run again.
     if [ -n "$ocs_live_run_tty" ]; then
       # ocs_live_run_tty is like: /dev/tty2, /dev/pts/2 (very unlikely)
       ttys="$(LC_ALL=C echo $ocs_live_run_tty | sed -e "s|/dev/||g")"
     else
       ttys="tty1"
     fi
     for i in $ttys; do
       tty_bash_id="$(LC_ALL=C ps -t $i | grep bash | awk -F" " '{print $1}')"
       kill -9 $tty_bash_id
     done
     ;;
  *) echo ;;
esac
