#!/bin/sh

if test "`whoami`" != "root" ; then
  echo "Error! You must be root or sudoer to execute this command"
  exit 1
fi

MAX_REOPEN=$1;
USE_MINITERM=n
USE_SCREEN=n
LOCK_DIR=/tmp/cli.lock
LOCK_FILE=$LOCK_DIR/owner
EXIT_CHAR=3
EXIT_CHAR_HINT="^c"

SERVICE_NAME=qnos
PST_FILE=/tmp/cli_terminal
MINITERM_FILE=/mnt/application/miniterm.py
CONFIG_FILE=/etc/${SERVICE_NAME}.conf

. ${CONFIG_FILE}
if [ "$FP_CLI_CTRL_C_EXIT_DISABLE" = "1" ]; then
 EXIT_CHAR=26
 EXIT_CHAR_HINT="^z"
fi

usage()
{

cat << __START__

 Usage: qnos-console [-r] [-h]

 This command opens pseudo terminal to qnos and provide CLI access
 to user. If qnos service is not running, this command will wait for 
 service to start. User can come out of this command by pressing ${EXIT_CHAR_HINT} at any 
 point of time.

 COMMAND LINE OPTIONS

 -r 
     Retry to connect to pseudo terminal in the event
      qnos restarts or user tries to exit.  User will have to 
     press ${EXIT_CHAR_HINT} twice to completely exit.

 -f
     Detect and close if a session is already open
     
 -h 
     Help. Prints this text. 

 Note:
 If python is not installed on the system, this command launches a GNU screen 
 session to access the pseudo terminal. Use GNU screen commands to exit.

__START__

}

while getopts "hrf" opt;
do
    case "$opt" in
    h|\?)
        usage
        exit 0
        ;;
    r)  INFI_LOOP="Y"
        ;;
    f)  FORCE=1
        ;;
    esac
done

clean_lock()
{
   if [ -e $LOCK_FILE ]; then
      OWNER=`cat $LOCK_FILE`
      if [ "$OWNER" != "$$" ]; then
        kill -9  $OWNER > /dev/null 2>&1
        pkill -f $MINITERM_FILE > /dev/null 2>&1
      fi
   fi
   rm -rf $LOCK_DIR
}

take_lock()
{
  if [ "$FORCE" = "1" ]; then
     clean_lock
  fi

  mkdir $LOCK_DIR > /dev/null 2>&1
  if [ $? -eq 0 ]; then
     # Save PID into lock file
     echo $$ > $LOCK_FILE
  else
       echo "Error! Detected open console session. Use -f option to override."
       exit 1
  fi
}

give_lock()
{
   if [ -e $LOCK_FILE ]; then
      OWNER=`cat $LOCK_FILE`
      if [ "$OWNER" = "$$" ]; then
        rm -rf $LOCK_DIR
      fi
   fi
}

if [ -e /usr/bin/python ]; then
   USE_MINITERM=y
else
   USE_SCREEN=y
fi

while : ; 
do
  # /* QB: G#2235 2023/3/7 */
  printf "\nInitializing console session.\n";
  # /* QE: G#2235 */
  #/* QB: B#1550 2018/01/04 */
  if [ -e /usr/bin/snap ]; then
    if ! systemctl -q is-active snap.${SNAP_NAME}.icos ; then
      echo "Waiting for ${SERVICE_NAME} service to be operational."
    fi
  elif [ -e /bin/systemctl ]; then
    if ! systemctl -q is-active ${SERVICE_NAME} ; then
      echo "Waiting for ${SERVICE_NAME} service to be operational."
    fi
  else
    if [ "$(status ${SERVICE_NAME} | grep -i running)" = "" ]; then
      echo "Waiting for ${SERVICE_NAME} service to be operational."
    fi
  fi

  if [ -e /usr/bin/snap ]; then
    until [ -e ${PST_FILE} ] && \
          [ -c $(cat ${PST_FILE} | cut -d' ' -f4) ] && \
          systemctl -q is-active snap.${SNAP_NAME}.icos
    do
      sleep 0.5;
    done
  elif [ -e /bin/systemctl ]; then
    # /* QB: G#2235 2023/3/7 */
    counter=0;    
    until [ $counter -lt 200 ] && \
          [ -e ${PST_FILE} ] && \
          [ -c $(cat ${PST_FILE} | cut -d' ' -f4) ] && \
          systemctl -q is-active ${SERVICE_NAME}
    do
      sleep 0.5;
      printf ".";
      counter=$((counter+1))
      if [ $counter -ge 200 ]; then
        printf "\n${SERVICE_NAME} service is deactivating! Closing console session.\n";
        exit 1;
      fi
    done
    # /* QE: G#2235 */
  else
    until [ -e ${PST_FILE} ] && \
          [ -c $(cat ${PST_FILE} | cut -d' ' -f4) ] && \
          [ "$(status ${SERVICE_NAME} | grep -i running)" != "" ]
    do
      sleep 0.5;
    done
  fi
  #/* QE: B#1550 */
  PST_TERM=`cat ${PST_FILE} | cut -d' ' -f4`
  # /* QB: G#2235 2023/3/7 */
  printf "\nConnecting to ${PST_TERM}. Press ${EXIT_CHAR_HINT} to exit\n\n";
  # /* QE: G#2235 */

  
  if [ ! -w ${PST_TERM} ]; then
     echo "Access Denied! Closing console session."
     exit 0;
  fi

  take_lock
  if [ "${USE_SCREEN}" = "y" ]; then
     if [ "$(screen -ls | grep ${SERVICE_NAME})" != "" ]; then
       screen -x ${SERVICE_NAME}
     else
       screen -S ${SERVICE_NAME} ${PST_TERM}
     fi
     screen -wipe
  else
     /usr/bin/python ${MINITERM_FILE} -q --exit-char=${EXIT_CHAR} -p ${PST_TERM} 2> /dev/null
     stty sane
  fi
  give_lock
  if [ "$INFI_LOOP" != "Y" ]; then
    printf "\nClosing console session.\n"
    exit 0;
   else
    printf "\nClosing console session. Press ${EXIT_CHAR_HINT} in 5s to exit\n"
    sleep 5
  fi
done

give_lock
exit 0

