#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# License: GPL
# //NOTE// Do not put poweroff/reboot in this program since it's run in jfbterm/bterm. We separate the final action from ocs-live-final-action. Otherwise if the poweroff command run in jfbterm/bterm, the Debian live "Press Enter" message after poweroff/shutdown command is issued might be coverd by jfbterm/bterm and user will not have any idea what's happening after choose poweroff/reboot. 

# 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

# Settings
# Default we will check if $ocsroot is a mountpoint after the mount action is done.
chk_ocsroot_mountpont="yes"
cmdl_file_def="/proc/cmdline"

# Functions
USAGE() {
    echo "$ocs - To choose the final action (poweroff, reboot, command line prompt...) and put the output in a file"
    echo "Usage:"
    echo "To run $ocs:"
    echo "$ocs input_status"
    echo "input_status: 0: normal, 99: cmd, others: fail"
    echo "Ex:"
    echo "To choose the final action and give the input status as 99"
    echo "   $ocs 99"
} # end of USAGE
#
ask_final_action() {
  # ocs_postmode_prompt is loaded from ocs-live.conf.
  if [ "$ocs_postmode_prompt" = "cmd" ]; then
    echo "$msg_clone_finished_choose_to:"
    echo "(0) $msg_poweroff"
    echo "(1) $msg_reboot"
    echo "(2) $msg_enter_cml"
    echo "(3) $msg_run_clonezilla_live_again"
    if mountpoint $ocsroot &>/dev/null; then
      echo "(4) $msg_run_clonezilla_live_again_but_keep_mounted_repository"
      echo "(5) $msg_run_clonezilla_live_again_but_remounted_subdir"
    fi
    echo -n "[2] "
    read final_action_no
    case "$final_action_no" in
      0) final_action="poweroff";;
      1) final_action="reboot";;
      3) final_action="rerun1";;
      4) final_action="rerun2";;
      5) final_action="rerun3";;
      *) final_action="cmd";;
    esac
  else
    # Default to use TUI mode
    TMP="$(mktemp /tmp/ocs_final_act.XXXXXX)"
    
    if mountpoint $ocsroot &>/dev/null; then
      repo_dev_="$(findmnt -Un -o source -T $ocsroot)"
      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")"
      rerun3_ocs_with_repo_mounted_1="rerun3"
      rerun3_ocs_with_repo_mounted_2="$(rep_whspc_w_udrsc "$msg_run_clonezilla_live_again_but_remounted_subdir: $repo_dev_")"
    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 \
      $rerun3_ocs_with_repo_mounted_1 $rerun3_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
  fi
} # end of ask_final_action
#
do_ocs_live_run_final() {
  # //NOTE// Do not put poweroff/reboot in this program since it's run in jfbterm/bterm. We separate the final action from ocs-live-final-action. Otherwise if the poweroff command run in jfbterm/bterm, the Debian live "Press Enter to continue" message after poweroff/shutdown command is issued might be coverd by jfbterm/bterm and user will not have any idea what's happening after choose poweroff/reboot. 
  [ -n "$final_action" ] && echo "The next step: $final_action"
  case "$final_action" in
    poweroff) unmount_mounted_fs_before_ocs_live_reboot
       ocs-park-disks
       echo -n 'Will poweroff (Press Ctrl-C to abort)... '
       countdown 7
       poweroff $HALT_REBOOT_OPT ;;
    reboot) unmount_mounted_fs_before_ocs_live_reboot
       ocs-park-disks
       echo -n 'Will reboot (Press Ctrl-C to abort)... '
       countdown 7
       reboot $HALT_REBOOT_OPT ;;
    rerun*) # umount the clonezilla home dir
       if [ "$final_action" = "rerun1" ]; then
         echo "Completely start over, so umounting $ocsroot..."
	 # Clean tag file for ocs-live-repository so it can be remounted again.
	 rm -f /var/lib/clonezilla/ocs-live-repository
         unmount_mounted_fs_before_ocs_live_reboot
       elif [ "$final_action" = "rerun3" ]; then
         echo "$msg_remount_subdir"
	 ocs-live-bind-mount
         [ "$chk_ocsroot_mountpont" = "yes" ] && check_if_ocsroot_a_mountpoint
       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
       ;;
    cmd) echo "Now enter command line prompt..."
       ;;
    *) echo "Now run: $final_action"
       $final_action
       ;;
  esac
} # end of do_ocs_live_run_final
#
decide_final_action_from_cmdline_and_user_assign() {
  # First find if ocs_final_action is assigned in cmdline
  parse_cmdline_option -c $cmdl_file "ocs_final_action"
  if [ -n "$ocs_final_action" ]; then
    final_action="$ocs_final_action"
  fi
  # Then find if user has assigned it in ocs-sr. This may overwrite the one assigned in boot parameter.
  if [ -e /var/lib/clonezilla/ocs-vars ]; then
    . /var/lib/clonezilla/ocs-vars
    if [ -n "$postaction" ]; then
      final_action="$postaction"
    fi
  fi
} # end of decide_final_action_from_cmdline_and_user_assign

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

ocs=`basename $0`
#
while [ $# -gt 0 ]; do
 case "$1" in
   -c|--cmdline-file)
      shift
      if [ -z "$(echo $1 |grep ^-.)" ]; then
        # skip the -xx option, in case 
        cmdl_file="$1"
        shift
      fi
      [ -z "$cmdl_file" ] && echo "-c is used, but no cmdl_file assigned." && exit 1
      ;;
   -*)     echo "${0}: ${1}: invalid option" >&2
           USAGE >& 2
           exit 2 ;;
   *)      break ;;
 esac
done

#
input_status="$1"

ask_and_load_lang_set $ocs_lang

# check DIA
check_DIA_set_ESC $DIA

#
[ -z "$cmdl_file" ] && cmdl_file="$cmdl_file_def"
if [ ! -e "$cmdl_file" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "Kernel cmdline file ($cmdl_file) does _NOT_ exist!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo "$msg_program_stop!"
  exit 1
fi

if [ -n "$input_status" ]; then
  # The input status is the return code
  if [ "$input_status" -eq 0 ]; then
    # Normal exit.
    decide_final_action_from_cmdline_and_user_assign
  elif [ "$input_status" -eq 99 ]; then
    final_action="cmd"
  else
    # Fail. Exit code is not 0
    final_action="choose"
  fi
else
  # input status unknown.
  decide_final_action_from_cmdline_and_user_assign
fi

# If final_action is still unknown or is "choose", ask it.
if [ -z "$final_action" -o "$final_action" = "choose" ]; then
  ask_final_action
fi

do_ocs_live_run_final
