#!/bin/sh
#-------------------------------------------------------------------------------
# charon_menu_console
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2022 STROMASYS.
# All rights reserved.
#
#set -x
VERSION=1.31

function The_End
{
  tput rmacs
  tput sgr0
  echo "$1"
  exit
}

trap 'echo;The_End "Aborted."' 1 2 9 14 15

. `dirname $0`/charon_common
. `dirname $0`/charon_common_menu

get_preferences

SVCNAME="charon_gstart"

LOGFLIST="${CHARONDIR}/utils/charon_logchk.list"
BOOTLIST="${CHARONDIR}/utils/charon_gstart.boot"

test -e ${HOME}/.charonconslogdir && CONSLOGDIR=`cat ${HOME}/.charonconslogdir`
test -z "${CONSLOGDIR}" && CONSLOGDIR="${CHARONDIR}/log"

INSBLD=`rpm -q charon-license 2>/dev/null | cut -f4 -d'-' | cut -f1 -d'.'`
INSBLD=${INSBLD:-0}

function display_hr
{
  if test "${SEMIGRAPH}" = "enabled"
  then
    tput smacs
    echo "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"
    tput rmacs
  else
    echo "--------------------------------------------------------------------------------"
  fi
}

function display_consolelogs
{
  if test `grep -v ^# ${BOOTLIST} | wc -l` -eq 0
  then 
    tput bold
    echo "Guests list is empty."
    tput sgr0
    return
  fi

  while test 1
  do
    if test `grep -v ^# ${BOOTLIST} | wc -l` -eq 1
    then
      ANS=1
    else
      display_header "View console logs"
      display_guestslist -num -console
      echo
      echo -n "${FGBLUEBOLD}Choice ('q' to quit):[0m "
      read ANS
    fi  
    case "${ANS}"
    in
      q)
        break
        ;;
      *)
        if test -n "${ANS}"
        then
          if test -z "`echo ${ANS} | tr -d [0123456789]`"
          then
            if test ${ANS} -lt 1 -o ${ANS} -gt `grep -v ^# ${BOOTLIST} | wc -l`
            then
              tput bold
              echo "Incorrect value, out of range."
              tput sgr0
              Press_Enter
            else
              echo
              CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`
              CHARON_EXE=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f1 -d';'`
              CFGCONSLOG=`grep -v ^# ${CFG} | grep "set.*OPA[0-9].*log.*=" | cut -f2 -d'=' | tr -d "'" | tr -d '"' | tr -d " "`

              CFGBASE=`basename ${CFG} | sed "s=\.cfg==g"`
              CONSOLELOG=""

              if test -z "${CFGCONSLOG}"
              then
                NUMOFLOGS=`ls ${CONSLOGDIR}/console.${CFGBASE}.log ${CONSLOGDIR}/console.${CFGBASE}.log.upto*[0-9] 2>/dev/null | wc -l`
              else
                if test -d ${CFGCONSLOG}
                then
                  CONFIG_NAME=`grep -v ^# ${CFG} | grep "set.*session.*configuration_name.*=" | cut -f2 -d'=' | tr -d "'" | tr -d '"' | tr -d " "`
                  if test -n "${CONFIG_NAME}"
                  then
                    NUMOFLOGS=`ls ${CFGCONSLOG}/${CONFIG_NAME}-OPA*-*.log 2>/dev/null | wc -l`
                    FINDLOGS="${CFGCONSLOG}/${CONFIG_NAME}-OPA*-*.log"
                  else
                    HW_MODEL=`grep -v ^# ${CFG} | grep "set.*session.*hw_model.*=" | cut -f2 -d'=' | tr -d "'" | tr -d '"'`
                    if test -n "${HW_MODEL}"
                    then
                      NUMOFLOGS=`ls ${CFGCONSLOG}/${HW_MODEL}-OPA*-*.log 2>/dev/null | wc -l`
                      FINDLOGS="${CFGCONSLOG}/${HW_MODEL}-OPA*-*.log"
                    else
                      tput bold
                      echo "Rotating console log file detected without configuration_name nor hw_model"
                      echo "specified."
                      echo
                      echo "Cannot continue."
                      tput sgr0
                      Press_Enter
                      return
                    fi
                  fi
                else
                  NUMOFLOGS=1
                fi
              fi

              case "${NUMOFLOGS}"
              in 
                0)
                  tput bold
                  echo "No console log file found in ${CONSLOGDIR} folder."
                  tput sgr0
                  Press_Enter
                  ;;
                1)
                  if test -z "${CFGCONSLOG}"
                  then
                    CONSOLELOG=`ls ${CONSLOGDIR}/console.${CFGBASE}.log ${CONSLOGDIR}/console.${CFGBASE}.log.upto*[0-9] 2>/dev/null`
                    CSLTYP="(file)"
                  else
                    if test -d ${CFGCONSLOG}
                    then
                      CONFIG_NAME=`grep -v ^# ${CFG} | grep "set.*session.*configuration_name.*=" | cut -f2 -d'=' | tr -d "'" | tr -d '"'`
                      if test -n "${CONFIG_NAME}"
                      then
                        CONSOLELOG=`ls ${CFGCONSLOG}/${CONFIG_NAME}-OPA*-*.log 2>/dev/null`
                      else
                        HW_MODEL=`grep -v ^# ${CFG} | grep "set.*session.*hw_model.*=" | cut -f2 -d'=' | tr -d "'" | tr -d '"'`
                        CONSOLELOG=`ls ${CFGCONSLOG}/${HW_MODEL}-OPA*-*.log 2>/dev/null`
                      fi
                      CSLTYP="(folder/rotating file)"
                    else
                      CONSOLELOG=${CFGCONSLOG}
                      CSLTYP="(file)"
                    fi
                  fi
                  echo
                  test -z "${CONSOLELOG}" && CSLTYP=""
                  echo "Found: ${CONSOLELOG:-None} ${CSLTYP}"
                  ;;
                *)
                  echo
                  tput bold
                  echo "${FGBLUE}Console logs (sorted by date ascending)[0m"
                  tput sgr0
                  display_hr
                  >/tmp/charon_menu_console.tmp
                  typeset -i I=0

                  if test -z "${CFGCONSLOG}"
                  then
                    ls -1tr ${CONSLOGDIR}/console.${CFGBASE}.log ${CONSLOGDIR}/console.${CFGBASE}.log.upto*[0-9] 2>/dev/null | while read LINE
                    do
                      I=I+1
                      printf "%2d - " $I
                      echo ${LINE} >>/tmp/charon_menu_console.tmp
                      L1=`basename ${LINE} | sed "s=\(^console\.\)\(.*\)\(\.log.*\)=\2=g"`
                      echo -n "${L1} "
                      if test -z "`echo ${LINE} | grep '\.upto[0-9]'`"
                      then
                        echo "${FGBLUEBOLD}(current)[0m"
                      else
                        L2=`echo ${LINE} | sed "s=\(^.*\.upto\)\(.*$\)=\2=g" | sed "s=-= =3"`
                        L21=`echo ${L2} | cut -f1 -d' '`
                        L22=`echo ${L2} | cut -f2 -d' ' | sed "s=\(^..\)\(..\)\(..$\)=\1:\2:\3=g"`
                        echo "/ up to ${L21} ${L22}"
                      fi
                    done
                  else
                    /usr/sbin/lsof +D ${CFGCONSLOG} >/tmp/charon_menu_console.lsof.tmp 2>/dev/null
                    ls -1trp ${FINDLOGS} 2>/dev/null | tail -20 | while read LINE
                    do
                      I=I+1
                      printf "%2d - " $I
                      echo ${LINE} >>/tmp/charon_menu_console.tmp
                      echo -n "`basename ${LINE}` (`wc -l ${LINE} | awk '{print $1}'` lines)"
                      if test -n "`grep ${LINE}$ /tmp/charon_menu_console.lsof.tmp`"
                      then
                        echo " ${FGBLUEBOLD}(current)[0m"
                      else
                        echo
                      fi
                    done
                  fi
                  echo

                  while test 1
                  do
                    printf "Select the console log to view ('q' to quit) : "
                    read ANS
                    case "${ANS}"
                    in
                      q)
                        break
                        ;;
                      *)
                        if test -n "${ANS}"
                        then
                          if test -z "`echo ${ANS} | tr -d [0123456789]`"
                          then
                            if test ${ANS} -lt 1 -o ${ANS} -gt `cat /tmp/charon_menu_console.tmp | wc -l`
                            then
                              tput bold
                              echo "Incorrect value, out of range."
                              tput sgr0
                              sleep 2
                              tput cuu1;tput el
                            else
                              CONSOLELOG=`cat /tmp/charon_menu_console.tmp | head -${ANS} | tail -1`
                              if test `cat ${CONSOLELOG} | wc -l` -eq 0
                              then
                                tput bold
                                echo "File is empty..."
                                tput sgr0
                                sleep 2
                                tput cuu1;tput el
                              else
                                break
                              fi
                            fi             
                          else
                            tput bold
                            echo "Incorrect value, must be numeric."
                            tput sgr0
                            sleep 2
                            tput cuu1;tput el
                          fi
                        fi
                        tput cuu1;tput el
                        ;;
                    esac
                  done
                  ;;
              esac

              if test -n "${CONSOLELOG}"
              then
                ask_editor
                if test -n "${EDI}"
                then
                  cat -v ${CONSOLELOG} >/tmp/`basename ${CONSOLELOG}`.shownonprinting
                  ${EDI} /tmp/`basename ${CONSOLELOG}`.shownonprinting 2>/dev/null
                fi
              fi

              test `grep -v ^# ${BOOTLIST} | wc -l` -eq 1 && break
            fi
          else
            tput bold
            echo "Incorrect value, must be numeric."
            tput sgr0
            sleep 2
            tput cuu1;tput el
          fi
        else
          tput bold
          echo "Incorrect value, must be numeric."
          tput sgr0
          Press_Enter
        fi
        ;;
    esac
  done
}

function disp_header
{
  display_header "Connection to guest console"
}

#--- .telnetrc preparation for 'telnet' if installed
if test ! -e ${HOME}/.telnetrc -a -e /usr/bin/telnet
then
  disp_header
  echo
  while test 1
  do
    echo   "Do you want to create the .telnetrc file for character"
    printf "mode [recommended] (y/n) ? "
    read ANS
    case "${ANS}"
    in
      y)
        echo "DEFAULT" >${HOME}/.telnetrc
        echo "	mode char" >>${HOME}/.telnetrc
        break
        ;;
      n)         
        break
        ;;
      *)
        tput cuu1
        tput cuu1;tput el
        ;;
    esac
  done
fi

#--- Session preparation for 'putty' if installed
PUTTYHOME=$HOME/.config/putty/sessions
if test -e /usr/bin/putty
then
  test -e ${PUTTYHOME} || mkdir -p ${PUTTYHOME}
  if test ! -e ${PUTTYHOME}/CHTERM-VT100
  then
    if test -e ${CHARONDIR}/putty/sessions/CHTERM-VT100
    then
      cp ${CHARONDIR}/putty/sessions/CHTERM-VT100 ${PUTTYHOME}
    else
      if test -e ${CHARONDIR}/utils/putty_sessions/CHTERM-VT100
      then
        cp ${CHARONDIR}/utils/putty_sessions/CHTERM-VT100 ${PUTTYHOME}
      else
        if test "${CONSOLEMODE}" = "putty"
        then
          echo "[46m[30m WARNING [0m 'putty' is installed on this system and"
          echo "          selected as default mode but the 'CHTERM-VT100' file cannot"
          echo "          be found in Charon kit."
          echo "          Please either get the file from Stromasys or change the default"
          echo "          mode to 'telnet'."
          tput sgr0
          echo
          Press_Enter
          exit
        fi
      fi
    fi
  fi
fi

while test 1
do
  get_preferences
  test "$1" = "cmd" || display_header "Connection to guest console"

  if test `id -u` -ne 0
  then
    echo
    tput bold
    echo "Must be root !"
    tput sgr0
    echo
    Press_Enter
    exit 1
  fi

  test "$1" = "cmd" || display_guestslist -num -console
  echo
  if test `grep -v ^# ${BOOTLIST} | wc -l` -eq 0
  then 
    tput bold
    echo "Guests list is empty."
    tput sgr0
    break 
  fi

  test -e /usr/bin/putty  && OKPUTTY=1  || OKPUTTY=0
  test -e /usr/bin/telnet && OKTELNET=1 || OKTELNET=0

  if test ${OKTELNET} = 0 -a ${OKPUTTY} = 0
  then
    tput bold
    echo "[46m[30m WARNING [0m Nor 'telnet' nor 'putty' installed on this system".
    echo "          Cannot connect to console from this host."
    tput sgr0
    echo
    Press_Enter
    break
  fi
  
  if test "$1" = "cmd"
  then
    ANS=$2
  else
    echo " k- Kill active telnet connection(s) on console(s)"
    echo " v- View console log files"
    echo
    echo -n "${FGBLUEBOLD}Choice ('q' to quit):[0m "
    read ANS
  fi
  case "${ANS}"
  in
    q)
      break
      ;;
    v)
      display_consolelogs
      ;;
    k)
      echo
      for LINE in `cat ${BOOTLIST} 2>/dev/null`
      do
        CHARON_CFG=`echo ${LINE} | cut -f2 -d';'`
        CHARON_CFGBAS=`basename ${CHARON_CFG}|sed "s=\.cfg==g"`
        CHARON_BOO=`echo ${LINE} | cut -f3 -d';'`
        EMUCFG=`basename ${CHARON_EXE}`"/${CHARON_CFGBAS}"
        echo "- [1m${EMUCFG}[0m"

        CHK=`grep -v ^# ${CHARON_CFG} | grep -w load | grep -w virtual_serial_line | grep OPA`
        test -z "${CHK}" -a ${INSBLD} -ge 19103 && CHK=`grep -v ^# ${CHARON_CFG} | grep -w set | grep -w OPA0 | grep -w port`
        PORT=`echo ${CHK} | sed "s/[ \t]\{1,\}/ /g" | sed "s/ =/=/g" | sed "s/= /=/g" | sed "s=\(^.*port\=\)\([0-9]\{1,\}\)\(.*$\)=\2=g"`
        CNXOVERRIDE=`echo ${CHK} | sed "s/[ \t]\{1,\}/ /g" | sed "s/ =/=/g" | sed "s/= /=/g" | tr [:upper:] [:lower:] | grep "connection_override=enable"`

        echo -n "  ${FGBLUE}Port:[0m ${PORT:-<Unknown>}"
        if test -n "${CNXOVERRIDE}"
        then
          echo " ([32mCNX override ON[30m)"
        else
          echo
        fi
        KACTION="kill these PID(s)"

        if test -n "${PORT}"
        then
          if test -n "`netstat -an 2>/dev/null | grep -w ${PORT} | grep ESTABLISHED`"
          then
            CHK=`ps -ef | grep telnet | grep -e localhost -e 127.0.0.1 | grep ${PORT}$ | awk '{print $2}' | tr "\n" " "`
            if test -n "${CHK}"
            then
              echo "  -> [31mConsole locked by 'telnet' pid(s) ${CHK}[0m"
              while test 1
              do
                echo -n "     Do you want to ${KACTION} (y/n) ? "
                read ANS
                case "${ANS}"
                in
                  n)
                    break
                    ;;
                  y)
                    kill -15 ${CHK}
                    break
                    ;;
                  *)
                    tput cuu1;tput el
                    ;;
                esac
              done
            else
              CHK=`ps -ef | grep putty | grep "\-P ${PORT}" | awk '{print $2}' | tr "\n" " "`
              if test -n "${CHK}"
              then
                echo "  -> [31mConsole locked by 'putty' pid(s) ${CHK}[0m"
                while test 1
                do
                  echo -n "     Do you want to ${KACTION} (y/n) ? "
                  read ANS
                  case "${ANS}"
                  in
                    n)
                      break
                      ;;
                    y)
                      kill -15 ${CHK}
                      break
                      ;;
                    *)
                      tput cuu1;tput el
                      ;;
                  esac
                done
              else
                CHK=`netstat -an | grep -w ${PORT} | grep ESTABLISHED | awk '{print $5}'`
                echo "  -> [31mLocked by foreign host `echo ${CHK}|cut -f1 -d':'`, port `echo ${CHK}|cut -f2 -d':'`[0m"
                echo "     Remote killing is not possible. Please use override option instead."
              fi
            fi
          else
            echo "  -> [32mConsole is not locked[0m"
          fi     
        else
          echo "  -> [31mConsole port is correcly defined[0m"
        fi
      done
      Press_Enter
      ;;
    *)
      if test -n "${ANS}"
      then
        if test -z "`echo ${ANS} | tr -d [0123456789]`"
        then
          if test ${ANS} -lt 1 -o ${ANS} -gt `grep -v ^# ${BOOTLIST} | wc -l`
          then
            tput bold
            echo "Incorrect value, out of range."
            tput sgr0
            Press_Enter
          else
            echo
            CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`
            CHARON_EXE=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f1 -d';'`

            if test `grep -c "^#INFO:" ${CFG}` -gt 0
            then
              display_hr
              echo "${FGBLUEBOLD}Configuration description:[0m"
              grep "^#INFO:" ${CFG} | sed "s=^#INFO:==g"
              echo
              display_hr
            fi

            CHK=`ps -ef | grep "${CHARON_EXE} -d ${CFG}" | grep -v grep`
            if test -n "${CHK}"
            then
              #test `grep -c "^#INFO:" ${CFG}` -gt 0 && Press_Enter
              test "$1" = "cmd" || Press_Enter

              CHK=`grep -v ^# ${CFG} | grep -w load | grep -w virtual_serial_line | grep OPA`
              printf "Console settings "
              test -z "${CHK}" -a ${INSBLD} -ge 19103 && CHK=`grep -v ^# ${CFG} | grep -w set | grep -w OPA0 | grep -w port`
              if test -n "${CHK}"
              then
                echo "correctly set to:"
                echo ${CHK}
                echo
                PORT=`echo ${CHK} | sed "s/[ \t]\{1,\}/ /g" | sed "s/ =/=/g" | sed "s/= /=/g" | sed "s=\(^.*port\=\)\([0-9]\{1,\}\)\(.*$\)=\2=g"`
                CNXOVERRIDE=`echo ${CHK} | sed "s/[ \t]\{1,\}/ /g" | sed "s/ =/=/g" | sed "s/= /=/g" | tr [:upper:] [:lower:] | grep "connection_override=enable"`
                echo -n "${FGBLUE}Port:[0m ${PORT:-<Unknown>}"
                if test -n "${CNXOVERRIDE}"
                then
                  echo " ([32mCNX override ON[30m)"
                  KACTION="override connection"
                else
                  echo
                  KACTION="kill the existing connection and connect now"
                fi

                if test -n "`netstat -anp | grep -w ${PORT} | grep ESTABLISHED`"
                then
                  while test 1
                  do 
                    if test -n "`netstat -anp | grep -w ${PORT} | grep -w -e telnet -e putty`"
                    then
                      echo "[31mA local connection is already active on port ${PORT}.[0m"
                      echo
                      printf "Do you want to ${KACTION} (y/n) ? "
                      read ANS
                      case "${ANS}"
                      in
                        y)
                          PID=`ps -ef|grep telnet|grep -e localhost -e 127.0.0.1|grep ${PORT}|grep -v script|grep -v SCREEN|awk '{print $2}'`
                          if test -n "${PID}"
                          then
                            test -z "${CNXOVERRIDE}" && kill -15 ${PID}
                          else
                            PID=`ps -ef | grep putty | grep "\-P ${PORT}" | awk '{print $2}' | tr "\n" " "`
                            if test -n "${PID}"
                            then
                              test -z "${CNXOVERRIDE}" && kill -15 ${PID}
                            else
                              tput bold
                              echo "Process not found on this host, please disconnect manually."
                              tput sgr0
                              echo
                              Press_Enter
                            fi
                          fi
                          break
                          ;;
                        n)
                          tput bold
                          if test -z "${CNXOVERRIDE}"
                          then
                            echo "Connection refused."
                            tput sgr0
                            sleep 2
                            break
                          else
                            echo "Connection aborted."
                            tput sgr0
                            sleep 2
                            break 2
                          fi
                          ;;
                        *)
                          tput cuu1;tput el
                          ;;
                      esac
                    else
                      echo "[31mA remote connection is already active on port ${PORT}:[0m"
                      echo
                      netstat -an | head -2
                      netstat -an | grep -w ${PORT} | grep ESTABLISHED
                      tput bold
                      echo "Please disconnect manually."
                      tput sgr0
                      echo
                      Press_Enter
                      break
                    fi
                  done
                fi
                if test -z "`netstat -anp | grep -w ${PORT} | grep ESTABLISHED`" -o -n "${CNXOVERRIDE}"
                then
                  #--- Depending on preferences, act upon console mode selected
                  GOCONSOLE=""
                  case "${CONSOLEMODE}"
                  in
                    "telnet")
                      if test ${OKTELNET} = 1
                      then
                        echo "Console mode: [1m'telnet'[0m"
                        GOCONSOLE="telnet"
                      else
                        echo "Console mode: [1m'telnet' defined in preferences but not installed[0m"
                        if test ${OKPUTTY} = 1
                        then
                          if test -n "${DISPLAY}"
                          then
                            echo "Console mode: [1m'putty' will be used instead[0m"
                            GOCONSOLE="putty"
                          fi
                        fi
                      fi
                      ;;
                    "putty")
                      if test ${OKPUTTY} = 1
                      then
                        if test -n "${DISPLAY}"
                        then
                          echo "Console mode: [1m'putty'[0m"
                          GOCONSOLE="putty"
                        else
                          echo "Console mode: [1m'putty' defined in preferences but no DISPLAY[0m"
                          if test ${OKTELNET} = 1
                          then
                            echo "Console mode: [1m'telnet' will be used instead[0m"
                            GOCONSOLE="telnet"
                          fi
                        fi
                      else
                        echo "Console mode: [1m'putty' defined in preferences but not installed[0m"
                        if test ${OKTELNET} = 1
                        then
                          echo "Console mode: [1m'telnet' will be used instead[0m"
                          GOCONSOLE="telnet"
                        fi
                      fi
                      ;;
                    "always_ask")
                      if test ${OKTELNET} = 1
                      then
                        if test ${OKPUTTY} = 1 -a -n "${DISPLAY}"
                        then
                          #--- Telnet OK and Putty OK
                          while test 1
                          do
                            echo -n "${FGBLUEBOLD}Please select how you want to connect: 1=telnet, 2=putty, q=quit : [0m"
                            read ANS
                            case "${ANS}"
                            in
                              1)
                                GOCONSOLE="telnet"
                                break
                                ;;
                              2)
                                GOCONSOLE="putty"
                                break
                                ;;
                              q)
                                exit
                                ;;
                              *)
                                tput cuu1
                                tput el
                                ;;
                            esac
                          done
                        else
                          #--- Telnet OK and Putty NOT OK
                          GOCONSOLE="telnet"
                        fi
                      else
                        if test ${OKPUTTY} = 1 -a -n "${DISPLAY}"
                        then
                          #--- Telnet NOT OK and Putty OK
                          GOCONSOLE="putty"
                        else
                          #--- Telnet NOT OK and Putty NOT OK
                          GOCONSOLE=""
                        fi
                      fi
                      ;;
                  esac

                  #--- Open the console (or not)
                  case "${GOCONSOLE}"
                  in
                    "telnet")
                      tput bold
                      cat <<EOF
${FGBLUE}To leave the console, press the escape character as shown below in the
line 'Escape character is...' and enter 'quit' at the 'telnet>' prompt.

Default escape character can be changed in the \$HOME/.telnetrc file under the
machine or DEFAULT paragraph with the command: set escape <newchar>
EOF
                      tput sgr0
                      if test -e $HOME/.telnetrc
                      then
                        if test `grep -w set $HOME/.telnetrc | grep -w escape | wc -l` -eq 1
                        then
                          echo -n "[46m[30m Current escape is [0m "
                          tput bold
                          grep -w set $HOME/.telnetrc | grep -w escape | awk '{print $3}'
                          tput sgr0
                        fi
                      fi
                      echo
                      CHK=`grep -w stop_on ${CFG} | grep -v ^# | grep OPA | awk -F'=' '{print $2}' | tr -d ' '`
                      if test -n "${CHK}"
                      then
                        echo "[46m[30m WARNING [0m [31mThe virtual machine can be powered off by pressing [1m${CHK}[0m"
                      fi
                      CHK=`grep -w break_on ${CFG} | grep -v ^# | grep OPA | grep -i 'Ctrl-P'`
                      if test -n "${CHK}"
                      then
                        echo "[46m[30m WARNING [0m [31mThe virtual machine can be stopped by pressing [1mCTRL-P[0m"
                      fi

                      CHK=`grep -v ^# ${CFG} | grep "set.*OPA[0-9].*log.*="`
                      if test -z "${CHK}"
                      then
                        CONSLOGFIL="${CONSLOGDIR}/console.`basename ${CFG} | sed "s=\.cfg==g"`.log"
                        if test -e ${CONSLOGFIL}
                        then
                          while test 1
                          do
                            LOGFRENEXT="upto"`date +%F-%H%M%S`
                            if test -e ${CONSLOGFIL}.${LOGFRENEXT}
                            then
                              sleep 1
                            else
                              mv -f ${CONSLOGFIL} ${CONSLOGFIL}.${LOGFRENEXT}
                              if test $? = 0
                              then
                                echo "Moved '${CONSLOGFIL}' to '${CONSLOGFIL}.${LOGFRENEXT}'."
                              else
                                echo "Failed to move '${CONSLOGFIL}' to '${CONSLOGFIL}.${LOGFRENEXT}'. Continuing..."
                              fi
                              break
                            fi
                          done  
                        fi

                        script -a -f -c "telnet localhost ${PORT}" ${CONSLOGFIL}
                        RET=$?
                      else
                        CONSLOGFIL="/tmp/console.`basename ${CFG} | sed "s=\.cfg==g"`.tmp.log"
                        script -f -c "telnet localhost ${PORT}" ${CONSLOGFIL}
                        RET=$?
                      fi
                      if test ${RET} != 0
                      then
                        stty sane
                        break
                      fi
                      display_hr
                      echo
                      ;;
                    "putty")
                      CHK=`grep -w stop_on ${CFG} | grep -v ^# | grep OPA | awk -F'=' '{print $2}' | tr -d ' '`
                      if test -n "${CHK}"
                      then
                        echo "[46m[30m WARNING [0m [31mThe virtual machine can be powered off by pressing [1m${CHK}[0m"
                      fi
                      CHK=`grep -w break_on ${CFG} | grep -v ^# | grep OPA | grep -i 'Ctrl-P'`
                      if test -n "${CHK}"
                      then
                        echo "[46m[30m WARNING [0m [31mThe virtual machine can be stopped by pressing [1mCTRL-P[0m"
                      fi

                      CHK=`grep -v ^# ${CFG} | grep "set.*OPA[0-9].*log.*="`
                      if test -z "${CHK}"
                      then
                        CONSLOGFIL="${CONSLOGDIR}/console.`basename ${CFG} | sed "s=\.cfg==g"`.log"
                        if test -e ${CONSLOGFIL}
                        then
                          while test 1
                          do
                            LOGFRENEXT="upto"`date +%F-%H%M%S`
                            if test -e ${CONSLOGFIL}.${LOGFRENEXT}
                            then
                              sleep 1
                            else
                              mv -f ${CONSLOGFIL} ${CONSLOGFIL}.${LOGFRENEXT}
                              if test $? = 0
                              then
                                echo "Moved '${CONSLOGFIL}' to '${CONSLOGFIL}.${LOGFRENEXT}'."
                              else
                                echo "Failed to move '${CONSLOGFIL}' to '${CONSLOGFIL}.${LOGFRENEXT}'. Continuing..."
                              fi
                              break
                            fi
                          done  
                        fi

                        /usr/bin/putty -load CHTERM-VT100 -P ${PORT} -title "`basename ${CFG} | sed "s=\.cfg==g"` - OPA0 console - port ${PORT}" -log ${CONSLOGFIL} &
                        RET=$?
                      else
                        CONSLOGFIL="/tmp/console.`basename ${CFG} | sed "s=\.cfg==g"`.tmp.log"
                        test -e ${CONSLOGFIL} && rm -f ${CONSLOGFIL}
                        /usr/bin/putty -load CHTERM-VT100 -P ${PORT} -title "`basename ${CFG} | sed "s=\.cfg==g"` - OPA0 console - port ${PORT}" -log ${CONSLOGFIL} &
                        RET=$?
                      fi
                      if test ${RET} != 0
                      then
                        stty sane
                        break
                      fi
                      display_hr
                      echo
                      ;;
                    *)
                      echo
                      tput bold
                      echo "Nor 'telnet' nor 'putty' available to open console !"
                      tput sgr0
                      Press_Enter
                      ;;
                  esac
                fi
              else
                tput bold
                echo "[31mnot defined correctly[0m. Please check configuration file."
                tput sgr0
                cat <<EOOP

The OPA0 console must be set to virtual_serial_line with port number on all
versions:
${FGBLUE}load virtual_serial_line OPA0 port=<port number>[0m

or, for version 4.9 and above, to:
${FGBLUE}set COM1 alias = OPA0 port = <port number>[0m

[1mwithout[0m any terminal application to execute (detached process).

EOOP
                Press_Enter
              fi
            else
              while test 1
              do
                ACTION=""
                CHK=`ps -ef | grep "${CHARON_EXE} -d ${CFG}" | grep -v grep`
                if test -n "${CHK}"
                then
                  break
                else
                  CHK=`ps -ef | grep "charon_gstart check ${CFG}" | grep -v grep`
                  if test -n "${CHK}"
                  then
                    ACTION="starting"
                  else
                    ACTION="start"
                    DISP_ACTION="[1m[32m${ACTION}[0m"
                  fi
                fi
                echo
                if test "${ACTION}" != "starting"
                then
                  printf "Guest is not running, do you want to ${DISP_ACTION} `basename ${CHARON_EXE}`/`basename ${CFG}` (y/n) : "
                  read CH
                  case "${CH}"
                  in
                    y)
                      echo
                      GUEST_CFGBAS=`basename ${CFG}|sed "s=\.cfg==g"`
                      if test "${GLOBALLOGMON}" = "enabled"
                      then
                        if test "`systemctl is-enabled charon_logmon_${GUEST_CFGBAS}.service 2>/dev/null`" = "enabled"
                        then
                          printf "${FGBLUE}Starting charon_logmon_${GUEST_CFGBAS}.service at "
                          date +"%d-%b-%Y %H:%M:%S"
                          tput sgr0
                          systemctl start charon_logmon_${GUEST_CFGBAS}.service
                          sleep 2
                        fi
                      fi
                      echo "[42m[30m Starting charon_${GUEST_CFGBAS}.service at "`date +"%d-%b-%Y %H:%M:%S"`" [0m"
                      tput sgr0
                      systemctl reset-failed charon_${GUEST_CFGBAS}.service
                      FollowServiceStatus start charon_${GUEST_CFGBAS}.service
                      systemctl start charon_${GUEST_CFGBAS}.service                                          
                      get_logfile ${CFG}
                      test "${LOGTAILST}" = "true" && tail_log_colored ${LOGF}
                      FollowServiceStatus stop charon_${GUEST_CFGBAS}.service
                      disp_header
                      sleep 2
                      break
                      ;;
                    n)
                      break
                      ;;
                    *)
                      tput cuu1;tput el
                      ;;
                  esac
                else
                  echo "[44m[37m Current state is starting, cannot start nor stop at the moment [0m"
                  break
                fi
              done
            fi
          fi
        else
          tput bold
          echo "Incorrect value, must be numeric."
          tput sgr0
          Press_Enter
        fi
      fi
      test "$1" = "cmd" && break
      ;;
  esac
done

exit
