#!/bin/bash
#-------------------------------------------------------------------------------
# charon_menu_gstart for Charon-PAR
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2023 STROMASYS.
# All rights reserved.
# Products: PAR
#set -x
VERSION=2.1

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

get_preferences

LOGFLIST="${CHARONDIR}/utils/charon_logchk.list"
BOOTLIST="${CHARONDIR}/utils/charon_gstart.boot"
GUESTSTOP="${CHARONDIR}/utils/charon_gstart.stop"
MONLOG="${CHARONDIR}/log/charon_gstart.log"
TAILCMD=`grep ^TAILCMD= ${CHARONDIR}/utils/charon_logchk 2>/dev/null | cut -f2 -d'=' | tr -d '"'`

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

function disp_header
{
  display_header "Virtual Machines Management"
}

function create_logmon_service
{
  if test -z "`grep ^${LOGF}$ ${LOGFLIST} 2>/dev/null`"
  then
    echo ${LOGF} >>${LOGFLIST}
    if test $? = 0
    then
      echo "Log file ${LOGF} added to log monitor service."
    else
      echo "[1mFailed to add ${LOGF} to log monitor service. Please check manually.[0m"
    fi
  else
    echo "Log file ${LOGF} was already added to log monitor service."
  fi

  GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`
  #--- Virtual machine log monitoring service creation
  SVC_DESCRI="CHARON log monitoring `basename ${GUEST_EXE}`/${GUEST_CFGBAS}"
  SVC_BEFORE="charon_${GUEST_CFGBAS}"
  SVC_WORKDI=`dirname ${LOGF}`
  SVC_LOGFIL=${LOGF}
  cat ${CHARONDIR}/utils/templates/charon_logmon_VIRTUALMACHINE.service | \
      sed -e "s=<SVC_DESCRI>=${SVC_DESCRI}=g" \
          -e "s=<SVC_BEFORE>=${SVC_BEFORE}=g" \
          -e "s=<SVC_WORKDI>=${SVC_WORKDI}=g" \
          -e "s=<SVC_LOGFIL>=${SVC_LOGFIL}=g" \
          >/etc/systemd/system/charon_logmon_${GUEST_CFGBAS}.service
  systemctl daemon-reload
  systemctl enable charon_logmon_${GUEST_CFGBAS}.service 2>/dev/null
  if test $? = 0
  then
    echo "Service charon_logmon_${GUEST_CFGBAS}.service is enabled."
  else
    echo "[1mFailed to enable service charon_logmon_${GUEST_CFGBAS}.service. Please check manually.[0m"
  fi

  if test -x /usr/sbin/aksusbd
  then
    if test ! -s /etc/systemd/system/charon_monusb.service
    then
      echo "Installing aksusbd monitoring service..."
      cp -f ${CHARONDIR}/utils/templates/charon_monusb.service /etc/systemd/system/charon_monusb.service
      systemctl daemon-reload
      systemctl enable  charon_monusb.service
      systemctl start   charon_monusb.service
      sleep 2
    else
      systemctl restart charon_monusb.service
    fi
  fi
}

#--------------------------------------------------------------------
# Check emulators path and swap between hppa and charon-par if needed
# (executable name depends on Charon version)
#--------------------------------------------------------------------
if test -s ${BOOTLIST}
then
  rm -f ${BOOTLIST}.check.tmp 2>/dev/null
  cat ${BOOTLIST} | while read LINE
  do
    GEXE=`echo ${LINE} | cut -f1 -d';'`
    GCFG=`echo ${LINE} | cut -f2 -d';'`
    GBOO=`echo ${LINE} | cut -f3 -d';'`
    if test -x ${GEXE}
    then
      echo ${LINE} >>${BOOTLIST}.check.tmp
    else
      GEXENEW="/opt/charon/bin/charon-par"
      test "${GEXE}" = "/opt/charon/bin/charon-par" && GEXENEW="/opt/charon/bin/hppa"
      test -n "${GEXENEW}" && GEXE=${GEXENEW}
      echo "${GEXENEW};${GCFG};${GBOO}" >>${BOOTLIST}.check.tmp
    fi
  done
  if test -n "`diff ${BOOTLIST} ${BOOTLIST}.check.tmp`"
  then
    mv -f ${BOOTLIST}.check.tmp ${BOOTLIST}
  else
    rm -f ${BOOTLIST}.check.tmp
  fi
fi

#--------------------------------------------------------------------
# Main loop
#--------------------------------------------------------------------
while test 1
do
  get_preferences
  test "$1" = "cmd" || disp_header
  test "$1" = "cmd" || echo
  if test `id -u` -ne 0
  then
    echo "[41m[37m ERROR [0m Must be root !"
    Press_Enter
    echo
    exit 1
  fi

  if test "$1" = "cmd"
  then
    CH="2"
  else
    display_guestslist
    UPDTOP="[31m[1m"
    test -s ${BOOTLIST} && UPDTOP=""

    echo
    tput bold
    echo "${FGBLUE}Available options[0m"
    tput sgr0
    display_hr
    cat <<EOF
1 - ${UPDTOP}Update guests list[0m              6 - View guest log file
2 - Start/stop guests               7 - Create/Edit guest stop script
3 - Connect to guest console        8 - Create/Edit guest pre-start script
4 - Edit configuration files        9 - Create/Edit guest check/run script
5 - Manage 'systemd' services

EOF
    printf "${FGBLUE}Enter your choice (enter to refresh, q to quit):[0m "
    read CH
    echo
  fi

  case "${CH}"
  in
    1)
      #---------------------------------------------------
      # Update guests list
      #---------------------------------------------------
      while test 1
      do
        tput bold
        echo "${FGBLUE}Available options[0m"
        tput sgr0
        display_hr
        UPDTOP="[31m[1m"
        test -s ${BOOTLIST} && UPDTOP=""
        cat <<EOF
1 - ${UPDTOP}Add guest[0m
2 - Remove guest
3 - Enable/Disable start at server boot
q - quit

EOF
        printf "${FGBLUE}Enter your choice:[0m "
        read CH
        echo
        case "${CH}"
        in
          1)
            #---------------------------------------------------
            # Add guest
            #---------------------------------------------------
            if test -x ${CHARONDIR}/bin/charon-par
            then
              GUEST_EXE=${CHARONDIR}/bin/charon-par
            else
              if test -x ${CHARONDIR}/bin/hppa
              then
                GUEST_EXE=${CHARONDIR}/bin/hppa
              else
                GUEST_EXE=""
              fi
            fi

            if test -z "${GUEST_EXE}"
            then
              echo "${BGORANGE} WARNING [0m No emulator executable found !"
              echo
              Press_Enter
            else
              while test 1
              do
                echo
                tput bold
                echo "${FGBLUE}Configuration file selection[0m"
                tput sgr0
                display_hr
                echo "Please enter the configuration file full path or:"
                echo "- 'l' to list available ones in the default directory"
                echo "- 'c' to clone an existing file or template"
                echo "- 'q' to quit"
                echo -n "${FGBLUE}Your choice:[0m "
                read CH
                echo
                case "${CH}"
                in
                  "")
                    echo
                    ;;
                  l)
                    tput bold
                    echo "${FGBLUE}Configuration files found[0m"
                    tput sgr0
                    display_hr
                    for CFG in "*.cfg;Configuration files found in the default folder" "*.cfg.template;Templates" "*.cfg.example;Examples"
                    do
                      CFGTYPE=`echo ${CFG}|cut -f2 -d';'`
                      echo "${FGBLUE}${CFGTYPE}[0m"
                      CFG=`echo ${CFG}|cut -f1 -d';'`
                      find ${CHARONDIR} -name ${CFG} | sort | while read LINE
                      do
                        echo -n "- ${LINE} / last modified on "
                        ls -l ${LINE} | awk '{print $6,$7,$8,$9,$10,$11}' | sed "s=${LINE}==g"
                      done
                    done
                    if test -s ${BOOTLIST}
                    then
                      echo "${FGBLUE}Managed systems configuration files[0m"
                      cat ${BOOTLIST} | while read LINE
                      do
                        LINE=`echo ${LINE} | cut -f2 -d';'`
                        echo -n "- ${LINE} / last modified on "
                        ls -l ${LINE} | awk '{print $6,$7,$8,$9,$10,$11}' | sed "s=${LINE}==g"
                      done
                    fi
                    ;;
                  q)
                    break 2
                    ;;
                  c)
                    while test 1
                    do
                      echo
                      printf "Enter `tput bold`source`tput sgr0` file (q to quit) : "
                      read FSOURCE
                      case "${FSOURCE}"
                      in
                        "")
                          ;;
                        q)
                          break
                          ;;
                        *)
                          if test -e ${FSOURCE}
                          then
                            echo -n "Last modified on "
                            ls -l ${FSOURCE} | awk '{print $6,$7,$8,$9,$10,$11}' | sed "s=${FSOURCE}==g"
                            while test 1
                            do
                              echo
                              printf "Enter `tput bold`target`tput sgr0` file (q to quit) : "
                              read FTARGET
                              case "${FTARGET}"
                              in
                                "${FSOURCE}")
                                  tput bold
                                  echo "Target file cannot be same as source file!"
                                  tput sgr0
                                  ;;
                                "")
                                  ;;
                                q)
                                  break
                                  ;;
                                *)
                                  if test -e ${FTARGET}
                                  then
                                    echo -n "File already exist, last modified on "
                                    ls -l ${FTARGET} | awk '{print $6,$7,$8,$9,$10,$11}' | sed "s=${FTARGET}==g"
                                    while test 1
                                    do
                                      echo
                                      printf "Do yo want to overwrite (y/n) ? "
                                      read CH
                                      case "${CH}"
                                      in
                                        y)
                                          echo "Copying '${FSOURCE}' to '${FTARGET}' ..."
                                          cp ${FSOURCE} ${FTARGET}
                                          test $? = 0 && echo "Done." || echo "`tput bold`Failed!`tput sgr0`"
                                          chmod u+w ${FTARGET} 2>/dev/ull
                                          break
                                          ;;
                                        n)
                                          break
                                          ;;
                                        *)
                                          tput cuu1;tput el
                                          ;;
                                      esac
                                    done
                                  else
                                    if test -n "`echo ${FTARGET} | grep \.cfg$`"
                                    then
                                      if test -z "`echo ${FTARGET} | grep '/'`"
                                      then
                                        FTARGET="${CHARONDIR}/cfg/${FTARGET}"
                                        echo "Target file name changed to: ${FTARGET}"
                                      fi
                                      while test 1
                                      do
                                        echo
                                        printf "Please confirm (y/n) ? "
                                        read CH
                                        case "${CH}"
                                        in
                                          y)
                                            echo "Copying '${FSOURCE}' to '${FTARGET}' ..."
                                            cp ${FSOURCE} ${FTARGET}
                                            test $? = 0 && echo "Done." || echo "`tput bold`Failed!`tput sgr0`"
                                            chmod u+w ${FTARGET} 2>/dev/ull
                                            break
                                            ;;
                                          n)
                                            break
                                            ;;
                                          *)
                                            tput cuu1;tput el
                                            ;;
                                        esac
                                      done
                                    else
                                      tput bold
                                      echo "File extension must be '.cfg' !"
                                      tput sgr0
                                    fi
                                  fi
                                  ;;
                              esac
                            done                                  
                          else
                            tput bold
                            echo "File does not exist."
                            tput sgr0
                          fi
                          ;;
                      esac
                    done
                    ;;
                  /*.cfg)
                    if test -e ${CH}
                    then
                      CHB=$(basename ${CH})
                      #--- Check unique full path cfg file
                      CHK1=$(grep -e ";${CH}$" -e ";${CH};" ${BOOTLIST})
                      #--- Check unique cfg file name
                      CHK2=$(grep -e "/${CHB}$" -e "/${CHB};" ${BOOTLIST})
                      if test -z "${CHK1}${CHK2}"
                      then
                        while test 1
                        do
                          echo -n "${FGBLUE}Select the startup type (1=Manual, 2=Automatic, q to quit) [1]:[0m "
                          read GUEST_BOO
                          case "${GUEST_BOO}"
                          in
                            1|"")
                              GUEST_BOO="N"
                              break
                              ;;
                            2)
                              GUEST_BOO="Y"
                              break
                              ;;
                            q)
                              break 2
                              ;;
                            *)
                              tput cuu1
                              tput el
                              ;;
                          esac
                        done

                        GUEST_CFG=${CH}

                        #--- Log file forced to "/logs" subfolder of cfg file folder
                        GUEST_LOG=`dirname ${GUEST_CFG}`"/logs/"`basename ${GUEST_CFG} | sed "s=cfg$=log=g"`
                        echo "Log file forced to: ${GUEST_LOG}"
                        GLOGDIR=`dirname ${GUEST_LOG}`
                        if test -e ${GLOGDIR}
                        then
                          if test -d ${GLOGDIR}
                          then
                            echo "Folder ${GLOGDIR} already exists..."
                          else
                            echo "Renaming regular file ${GLOGDIR} to ${GLOGDIR}.old ..."
                            mv -f ${GLOGDIR} ${GLOGDIR}.old
                            mkdir -p ${GLOGDIR}
                          fi
                        else
                          echo "Creating folder ${GLOGDIR} ..."
                          mkdir -p ${GLOGDIR}
                        fi
                        echo "${GUEST_EXE};${GUEST_CFG};${GUEST_BOO}" >>${BOOTLIST}
                        if test $? = 0
                        then
                          tput bold
                          echo "Guest added."
                          tput sgr0

                          GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`

                          #--- Virtual machine service creation
                          while test 1
                          do
                            cat <<EOSVRCRE
Please enter a short description of the service, 24 characters maximum,
alphanumeric only. If a description is specified, it will be forced to:
'${FGBLUE}CHARON $(basename ${GUEST_EXE})/${GUEST_CFGBAS} - <description>[0m'
otherwise it will be:
'${FGBLUE}CHARON $(basename ${GUEST_EXE})/${GUEST_CFGBAS}[0m'

EOSVRCRE
                            echo -n "${FGBLUE}Description:[0m "
                            read USR_DESCRI
                            USR_DESCRI=$(echo ${USR_DESCRI} | tr -d '$@%?!|`\\' | cut -c1-24)
                            if test -n "${USR_DESCRI}"
                            then
                              SVC_DESCRI="CHARON $(basename ${GUEST_EXE})/${GUEST_CFGBAS} - ${USR_DESCRI}"
                            else
                              SVC_DESCRI="CHARON $(basename ${GUEST_EXE})/${GUEST_CFGBAS}"
                            fi
                            echo
                            echo "Description is set to:"
                            echo "${FGBLUE}${SVC_DESCRI}[0m"
                            echo
                            echo -n "${FGBLUE}Continue with this description (y/n) ?[0m "
                            read ANS
                            case "${ANS}"
                            in
                              y|Y)
                                break
                                ;;
                              n|N)
                                echo
                                ;;
                              *)
                                tput cuu1;tput el
                                ;;
                            esac
                          done
                          SVC_AFTERM="charon_logmon_${GUEST_CFGBAS}.service"
                          SVC_CONFIG=${GUEST_CFG}
                          SVC_DIR=`dirname ${GUEST_CFG}`
                          cat ${CHARONDIR}/utils/templates/charon_VIRTUALMACHINE.service | \
                              sed -e "s=<SVC_DESCRI>=${SVC_DESCRI}=g" \
                                  -e "s=<SVC_AFTERM>=${SVC_AFTERM}=g" \
                                  -e "s=<SVC_DIR>=${SVC_DIR}=g" \
                                  -e "s=<SVC_CONFIG>=${SVC_CONFIG}=g" \
                                  -e "s=<SVC_LOG>=${GUEST_LOG}=g" \
                                  -e "s=<SVC_TIMOUTSTA>=${SVCTIMOUTSTART}=g" \
                                  -e "s=<SVC_TIMOUTSTO>=${SVCTIMOUTSTOP}=g" \
                                  >/etc/systemd/system/charon_${GUEST_CFGBAS}.service
                          systemctl daemon-reload
                          systemctl enable  charon_${GUEST_CFGBAS}.service 2>/dev/null
                          if test $? = 0
                          then
                            echo "Service charon_${GUEST_CFGBAS}.service is enabled."
                          else
                            echo "[1mFailed to enable service charon_${GUEST_CFGBAS}.service. Please check manually.[0m"
                          fi

                          echo
                          echo "${FGBLUE}Configuration file must be updated before starting the guest.[0m"
                          REEDIT=0
                          while test 1
                          do
                            echo
                            if test ${REEDIT} = 0
                            then
                              printf "Do you want to edit this file (y/n) ? "
                              read CH
                            else
                              CH="y"
                            fi
                            case "${CH}"
                            in
                              y|n)
                                if test "${CH}" = "y"
                                then
                                  ask_editor noquit
                                  REEDIT=0
                                  if test -n "${EDI}"
                                  then
                                    if test -z "`echo ${EDI}|grep vim`"
                                    then
                                      ${EDI} ${GUEST_CFG} 2>/dev/null
                                    else
                                      ${EDI} -u ${CHARONDIR}/utils/charoncfg.vimrc ${GUEST_CFG} 2>/dev/null
                                    fi
                                  fi
                                fi
                                echo
                                CFG=${GUEST_CFG}

                                OKSTART=1
                                echo "[44m[37m Checking console settings... [0m"
                                PORT=`grep -v ^# ${GUEST_CFG} | grep -e uart0.device.port -e gsc.lasi.uart.device.port | cut -f2 -d'=' | tr -d ":'\""`
                                if test -n "${PORT}"
                                then
                                  echo "Console port correctly set to: ${PORT}"
                                else
                                  tput bold
                                  echo "[41m[37m ERROR [0m Console port not found. Please correct the configuration file."
                                  tput sgr0
                                  OKSTART=0
                                fi

                                echo "[44m[37m Checking session log file settings... [0m"
                                get_logfile ${CFG}
                                if test -n "${LOGF}"
                                then
                                  echo "Log file is set to: ${FGBLUE}${LOGF-Full path not specified}[0m"
                                  if test -z "`echo ${LOGF} | grep '/'`"
                                  then
                                    echo
                                    echo "[41m[37m ERROR [0m The log file full path is not specified."
                                    echo "        Please update the configuration file."
                                    OKSTART=0
                                    Press_Enter
                                  else
                                    CHKD=`dirname ${LOGF}`
                                    if test ! -d ${CHKD}
                                    then
                                      echo "Making directory ${CHKD} ..."
                                      mkdir -p ${CHKD}
                                    fi
                                    test "${GLOBALLOGMON}" = "enabled" && create_logmon_service
                                  fi
                                else
                                  echo
                                  echo "[41m[37m ERROR [0m The log file full path is not specified."
                                  echo "        Please update the configuration file."
                                  OKSTART=0
                                  Press_Enter
                                fi
                                echo

                                check_vdisk_files ${CFG} display
                                echo

                                check_network_settings ${CFG} display

                                #-- Displays an alert if virtual machines are not in separate folders
                                ( for LINE in `grep -v ^# ${BOOTLIST}`
                                  do
                                    dirname `echo ${LINE} | cut -f2 -d';'`
                                  done ) | sort -u >${BOOTLIST}.tmp.$$
                                NBFOLD=`cat ${BOOTLIST}.tmp.$$ | wc -l`
                                NBGUES=`grep -v ^# ${BOOTLIST} | wc -l`
                                rm -f ${BOOTLIST}.tmp.$$ 2>/dev/null
                                if test ${NBFOLD} -ne ${NBGUES}
                                then
                                  echo
                                  echo "[41m[37m ERROR [0m There are virtual machines using the same folder !"
                                  echo "          This will cause files lock. Please update accordingly."
                                  echo
                                  OKSTART=0
                                fi

                                echo
                                while test 1
                                do
                                  printf "Do you want to start this guest (y/n) or re-edit the file (e) ? "
                                  read CH
                                  case "${CH}"
                                  in
                                    y|Y)
                                      test "${CH}" = "Y" && OKSTART=1
                                      if test ${OKSTART} = 1
                                      then
                                        REEDIT=0
                                        get_logfile ${GUEST_CFG}
                                        ###touch ${LOGF}
                                        GUEST_CFGBAS=`basename ${GUEST_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 3
                                            echo -n "Status: "
                                            systemctl is-active charon_logmon_${GUEST_CFGBAS}.service
                                          fi
                                          if test -x /usr/sbin/aksusbd
                                          then
                                            echo "Restarting aksusbd log monitor service..."
                                            systemctl restart charon_monusb.service
                                          fi
                                        fi
                                        echo "[42m[30m Starting charon_${GUEST_CFGBAS}.service at "`date +"%d-%b-%Y %H:%M:%S"`" [0m"
                                        FollowServiceStatus start charon_${GUEST_CFGBAS}.service
                                        systemctl start charon_${GUEST_CFGBAS}.service
                                        FollowServiceStatus stop charon_${GUEST_CFGBAS}.service
                                        test "${LOGTAILST}" = "true" && tail_log_colored ${LOGF}
                                        test ${AUTOSTOPLOGTAIL:-1} = 1 && Press_Enter
                                        disp_header
                                        sleep 2
                                        break
                                      else
                                        echo "[41m[37m ERROR [0m [31mConditions are not met to start the guest.[0m"
                                        Press_Enter
                                        tput cuu1;tput cuu1;tput cuu1;tput ed
                                      fi
                                      ;;
                                    n)
                                      REEDIT=0
                                      echo
                                      break
                                      ;;
                                    e)
                                      REEDIT=1
                                      break
                                      ;;
                                    *)
                                      tput cuu1;tput ed
                                      ;;
                                  esac
                                done
                                test ${REEDIT} = 0 && break
                                ;;
                              n)
                                break
                                ;;
                              *)
                                tput cuu1;tput el
                                ;;
                            esac
                          done
                        else
                          echo "[41m[37m ERROR [0m [31mFailed to add guest.[0m"
                        fi
                        break
                      else
                        if test -n "${CHK1}"
                        then
                          echo "${BGORANGE} WARNING [0m"
                          echo "${FGORANGE}Configuration file (full path) already exists in guests list, cannot be added![0m"
                        else
                          if test -n "${CHK2}"
                          then
                            echo "${BGORANGE} WARNING [0m"
                            echo "${FGORANGE}Configuration file name '$(echo ${CHB} | sed 's=\.cfg==g')' already exists in guests list, cannot be added![0m"
                          fi
                        fi
                      fi
                    else
                      echo "${BGORANGE} WARNING [0m"
                      echo "${FGORANGE}File does not exist, it is highly recommended to use the clone option[0m"
                    fi
                    ;;
                  *)
                    echo "${BGORANGE} WARNING [0m"
                    echo "${FGORANGE}Wrong file name. Must contain folder and extension .cfg[0m"
                    ;;
                esac
              done
            fi
            ;;
          2)
            #---------------------------------------------------
            # Remove guest
            #---------------------------------------------------
            while test 1
            do
              if test -s ${BOOTLIST}
              then
                if test $(grep -v ^# ${BOOTLIST} 2>/dev/null | wc -l) -gt 2
                then
                  display_guestslist -num -l
                else
                  display_guestslist -num
                fi
              fi
              echo
              NGUESTS=`grep -v ^# ${BOOTLIST} | wc -l`
              if test ${NGUESTS:-0} -eq 0
              then 
                tput bold
                echo "Guests list is empty."
                tput sgr0
                break
              fi
              if test ${NGUESTS:-0} -eq 1
              then
                ANS=1
              else  
                printf "Select the guest you want to remove (q to quit): "
                read ANS
                test "${ANS}" = "q" && break
              fi
              if test -n "${ANS}"
              then
                if test -z "`echo ${ANS} | tr -d [0123456789]`"
                then
                  if test ${ANS} -lt 1 -o ${ANS} -gt ${NGUESTS:-0}
                  then
                    tput bold
                    echo "Incorrect value, out of range."
                    tput sgr0
                  else
                    GUEST_EXE=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f1 -d';'`
                    GUEST_CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`
                    echo
                    while test 1
                    do
                      echo -n "Please confirm the removal of `basename ${GUEST_EXE}`/`basename ${GUEST_CFG}` (y/n) : "
                      read CH
                      case "${CH}"
                      in
                        y|Y)
                          echo
                          CHK=`ps -ef | grep -w ${GUEST_EXE} | grep "\-f ${GUEST_CFG}"`
                          if test -n "${CHK}"
                          then 
                            while test 1
                            do
                              echo
                              test ! -e ${GUESTSTOP} && echo "
No stop script found, emulator will be killed without proper shutdown !!!"
                              tput bold
                              printf "Do you want to stop the guest now (y/n) ? "
                              tput sgr0
                              read CH
                              case "${CH}"
                              in
                                y|Y)
                                  GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`
                                  echo "[41m[37m Stopping charon_${GUEST_CFGBAS}.service at "`date +"%d-%b-%Y %H:%M:%S"`" [0m"
                                  FollowServiceStatus start charon_${GUEST_CFGBAS}.service
                                  systemctl stop charon_${GUEST_CFGBAS}.service
                                  FollowServiceStatus stop charon_${GUEST_CFGBAS}.service
                                  sleep 3
                                  echo
                                  break
                                  ;;
                                n|N)
                                  break
                                  ;;
                               *)
                                  tput cuu1;tput el
                                  ;;
                              esac
                            done
                          else
                            echo "Guest is not running."
                          fi
                          echo "Removing from guests list..."
                          grep -v -e "^${GUEST_EXE};${GUEST_CFG}$" -e "^${GUEST_EXE};${GUEST_CFG};" ${BOOTLIST} >/tmp/charon_menu_gstart.tmp
                          mv -f /tmp/charon_menu_gstart.tmp ${BOOTLIST}
                          test $? = 0 && echo "Done." || echo "`tput bold`Failed.`tput sgr0`"
                          echo "Configuration file is kept in place."

                          GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`

                          get_logfile ${GUEST_CFG}
                          if test -n "${LOGF}"
                          then
                            if test -n "`grep ^${LOGF}$ ${LOGFLIST} 2>/dev/null`"
                            then
                              #--- Log monitoring service removal
                              grep -v ^${LOGF}$ ${LOGFLIST} >${LOGFLIST}.tmp
                              mv -f ${LOGFLIST}.tmp ${LOGFLIST}
                              if test "`systemctl is-active charon_logmon_${GUEST_CFGBAS}.service`" != "unknown"
                              then
                                systemctl stop    charon_logmon_${GUEST_CFGBAS}.service
                                systemctl disable charon_logmon_${GUEST_CFGBAS}.service
                                rm -f /etc/systemd/system/charon_logmon_${GUEST_CFGBAS}.service
                                systemctl daemon-reload
                              fi
                            fi
                          fi

                          #--- If the service is removed, the get_logfile does not work so remove logmon first
                          systemctl disable charon_${GUEST_CFGBAS}.service
                          rm -f /etc/systemd/system/charon_${GUEST_CFGBAS}.service
                          systemctl daemon-reload

                          break
                          ;;
                        n|N)
                          if test ${NGUESTS:-0} -eq 1
                          then
                            break 2
                          else
                            break
                          fi
                          ;;
                      esac
                    done
                  fi
                else
                  tput bold
                  echo "Incorrect value, must be numeric."
                  tput sgr0
                fi
              fi
            done
            ;;
          3)
            #---------------------------------------------------
            # Enable/Disable start at server boot
            #---------------------------------------------------
            while test 1
            do
              display_guestslist -num
              echo
              NGUESTS=`grep -v ^# ${BOOTLIST} | wc -l`
              if test ${NGUESTS:-0} -eq 0
              then 
                tput bold
                echo "Guests list is empty."
                tput sgr0
                break
              fi
              if test ${NGUESTS:-0} -eq 1
              then
                ANS=1
              else
                printf "Select the guest you want update (q to quit): "
                read ANS
                test "${ANS}" = "q" && break
              fi
              if test -n "${ANS}"
              then
                if test -z "`echo ${ANS} | tr -d [0123456789]`"
                then
                  if test ${ANS} -lt 1 -o ${ANS} -gt ${NGUESTS:-0}
                  then
                    tput bold
                    echo "Incorrect value, out of range."
                    tput sgr0
                  else
                    GUEST_EXE=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f1 -d';'`
                    GUEST_CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`
                    GUEST_BOO=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f3 -d';'`
                    if test "${GUEST_BOO:-Y}" = "Y"
                    then
                      NEW_BOO="N"
                      DSP_BOO="Manual"
                      NEW_COL="[31m"
                    else
                      NEW_BOO="Y"
                      DSP_BOO="Automatic"
                      NEW_COL="[32m"
                    fi
                    while test 1
                    do
                      echo
                      printf "Please confirm `basename ${GUEST_EXE}`/`basename ${GUEST_CFG}|sed 's=\.cfg==g'` boot change to '${NEW_COL}${DSP_BOO}[0m' (y/n) : "
                      read CH
                      case "${CH}"
                      in
                        y|Y)
                          rm -f ${BOOTLIST}.tmp 2>/dev/null
                          cat ${BOOTLIST} | while read LINE
                          do
                            REPL_EXE=`echo ${LINE} | cut -f1 -d';'`
                            REPL_CFG=`echo ${LINE} | cut -f2 -d';'`
                            REPL_BOO=`echo ${LINE} | cut -f3 -d';'`
                            if test "${REPL_EXE}" = "${GUEST_EXE}" -a "${REPL_CFG}" = "${GUEST_CFG}"
                            then
                              REPL_BOO=`echo ${NEW_BOO} | cut -c1`
                            fi
                            echo "${REPL_EXE};${REPL_CFG};${REPL_BOO}" >>${BOOTLIST}.tmp
                            GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`
                            if test "${REPL_BOO}" = "Y"
                            then
                              systemctl enable charon_${GUEST_CFGBAS}.service 2>/dev/null
                            else
                              systemctl disable charon_${GUEST_CFGBAS}.service 2>/dev/null
                            fi
                          done
                          mv -f ${BOOTLIST}.tmp ${BOOTLIST}
                          break
                          ;;
                        n|N)
                          if test ${NGUESTS:-0} -eq 1
                          then
                            break 2
                          else
                            break
                          fi
                          ;;
                        *)
                          tput cuu1;tput el
                          ;;
                      esac
                    done
                  fi
                else
                  tput bold
                  echo "Incorrect value, must be numeric."
                  tput sgr0
                fi
              fi
            done
            ;;
          q)
            break
            ;;
        esac
      done
      ;;
    2)
      #---------------------------------------------------
      # Start/stop guests
      #---------------------------------------------------
      while test 1
      do
        NGUESTS=`grep -v ^# ${BOOTLIST} | wc -l`
        if test "$1" != "cmd"
        then
          display_guestslist -num
          echo
          if test ${NGUESTS:-0} -eq 0
          then 
            tput bold
            echo "Guests list is empty."
            tput sgr0
            break
          fi
          if test ${NGUESTS:-0} -eq 1
          then
            ANS=1
          else
            printf "Select the guest you want to start/stop (q to quit, enter to refresh): "
            read ANS
            test "${ANS}" = "q" && break
          fi
        else
          ANS="$2"
        fi

        if test -n "${ANS}"
        then
          if test -z "`echo ${ANS} | tr -d [0123456789]`"
          then
            if test ${ANS} -lt 1 -o ${ANS} -gt ${NGUESTS:-0}
            then
              tput bold
              echo "Incorrect value, out of range."
              tput sgr0
              test "$1" = "cmd" && break 2
            else
              GUEST_EXE=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f1 -d';'`
              GUEST_CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`
              while test 1
              do
                CHK=`ps -ef | grep -w ${GUEST_EXE} | grep "\-f ${GUEST_CFG}"`
                if test -n "${CHK}"
                then
                  ACTION="stop"
                  DISP_ACTION="[1m[31m${ACTION}[0m"
                  test ! -e ${GUESTSTOP} && echo "
No stop script found, emulator will be killed without proper shutdown !!!"
                else
                  GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`
                  SVC_IS_ACTIVE=`systemctl is-active charon_${GUEST_CFGBAS} 2>/dev/null | cut -f1 -d'-' | tr [:lower:] [:upper:]`
                  if test "${SVC_IS_ACTIVE}" = "DEACTIVATING"
                  then
                    ACTION="stopping"
                  else
                    ACTION="start"
                    DISP_ACTION="[1m[32m${ACTION}[0m"
                  fi
                fi
                test "$1" = "cmd" || echo
                if test "${ACTION}" = "start" -o "${ACTION}" = "stop"
                then
                  if test "$1" = "cmd"
                  then
                    VMCMD=`echo $3|cut -c3-`
                    if test "${VMCMD}" != "${ACTION}"
                    then
                      echo -n "${BGORANGE}[WARN ][0m "
                      echo -n "Cannot ${VMCMD} `basename ${GUEST_EXE}`/`basename ${GUEST_CFG}`. Already "
                      test "${VMCMD}" = "start" && echo "started." || echo "stopped."   
                      break 2
                    fi
                    if test "${VMCMD}" = "stop"
                    then
                      echo -n "Please confirm you want to ${DISP_ACTION} `basename ${GUEST_EXE}`/`basename ${GUEST_CFG}` (y/n) : "
                      read CH
                    else
                      CH="y"
                    fi
                  else
                    echo -n "Please confirm you want to ${DISP_ACTION} `basename ${GUEST_EXE}`/`basename ${GUEST_CFG}` (y/n) : "
                    read CH
                  fi
                  case "${CH}"
                  in
                    y|Y)
                      echo
                      GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`
                      if test "${ACTION}" = "start"
                      then
                        echo -n "[42m[30m Starting"
                        systemctl reset-failed charon_${GUEST_CFGBAS}.service 2>/dev/null
                      else
                        echo -n "[41m[37m Stopping"
                      fi
                      echo " charon_${GUEST_CFGBAS}.service at "`date +"%d-%b-%Y %H:%M:%S"`" [0m"
                      FollowServiceStatus start charon_${GUEST_CFGBAS}.service
                      systemctl ${ACTION} charon_${GUEST_CFGBAS}.service
                      FollowServiceStatus stop charon_${GUEST_CFGBAS}.service
                      get_logfile ${GUEST_CFG}
                      test "${LOGTAILST}" = "true" -a "${ACTION}" = "start" && tail_log_colored ${LOGF}
                      if test "$1" != "cmd"
                      then
                        Press_Enter
                        disp_header 
                      fi
                      if test "${ACTION}" = "start"
                      then
                        get_logfile ${GUEST_CFG}
                      else
                        sleep 3
                        echo
                      fi
                      sleep 2
                      if test ${NGUESTS:-0} -eq 1
                      then
                        break 2
                      else
                        test "$1" = "cmd" && break 2 || break
                      fi
                      ;;
                    n|N)
                      if test ${NGUESTS:-0} -eq 1
                      then
                        break 2
                      else
                        test "$1" = "cmd" && break 2 || break
                      fi
                      ;;
                    *)
                      tput cuu1;tput el
                      ;;
                  esac
                else
                  echo "[44m[37m Current state is ${ACTION}, cannot start nor stop at the moment [0m"
                  echo
                  if test ${NGUESTS:-0} -eq 1
                  then
                    break 2
                  else
                    test "$1" = "cmd" && break 2 || break
                  fi
                fi
              done
            fi
          else
            tput bold
            echo "Incorrect value, must be numeric."
            tput sgr0
            test "$1" = "cmd" && break 2
          fi
        fi
      done
      test "$1" = "cmd" && break
      ;;
    3)
      #---------------------------------------------------
      # Connect to guest console
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_console
      ;;
    4)
      #---------------------------------------------------
      # Edit configuration files
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editcfg
      ;;
    5)
      #-------------------------------------------------------
      # Manage 'systemd' services
      #-------------------------------------------------------
      test ! -e ${BOOTLIST} && touch ${BOOTLIST}
      while test 1
      do
        display_guestslist -num
        echo
        NGUESTS=`grep -v ^# ${BOOTLIST} | wc -l`
        if test ${NGUESTS:-0} -eq 0
        then 
          tput bold
          echo "Guests list is empty."
          tput sgr0
          break
        fi
        if test ${NGUESTS:-0} -eq 1
        then
          ANS=1
        else
          printf "Select the guest you want to see service state (q to quit, enter to refresh): "
          read ANS
          test "${ANS}" = "q" && break
        fi
        if test -n "${ANS}"
        then
          if test -z "`echo ${ANS} | tr -d [0123456789]`"
          then
            if test ${ANS} -lt 1 -o ${ANS} -gt ${NGUESTS:-0}
            then
              tput bold
              echo "Incorrect value, out of range."
              tput sgr0
            else
              GUEST_EXE=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f1 -d';'`
              GUEST_CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`                
              GUEST_CFGBAS=`basename ${GUEST_CFG}|sed "s=\.cfg==g"`
              while test 1
              do
                echo "[44m[37m charon_${GUEST_CFGBAS}.service status [0m"
                systemctl -l --lines=20 --no-pager status charon_${GUEST_CFGBAS}.service
                echo
                echo -n "Do you want to edit the .service file (y/n) ? "
                read ANS
                case "${ANS}"
                in 
                  y)
                    ask_editor
                    if test -n "${EDI}"
                    then
                      ${EDI} /etc/systemd/system/charon_${GUEST_CFGBAS}.service 2>/dev/null
                      echo "Reloading systemd manager configuration..."
                      systemctl daemon-reload
                    fi
                    if test ${NGUESTS:-0} -eq 1
                    then
                      break 2
                    else
                      break
                    fi
                    ;;
                  n)
                    if test ${NGUESTS:-0} -eq 1
                    then
                      break 2
                    else
                      break
                    fi
                    ;;
                  *)
                    tput cuu1;tput el
                    ;;
                esac
              done
            fi
          else
            tput bold
            echo "Incorrect value, must be numeric."
            tput sgr0
          fi
        fi
      done
      echo
      ;;
    6)
      #---------------------------------------------------
      # View guest log file
      #---------------------------------------------------
      while test 1
      do
        display_guestslist -num
        echo
        NGUESTS=`grep -v ^# ${BOOTLIST} | wc -l`
        if test ${NGUESTS:-0} -eq 0
        then 
          tput bold
          echo "Guests list is empty."
          tput sgr0
          break
        fi
        if test ${NGUESTS:-0} -eq 1
        then
          ANS=1
        else
          printf "Select the guest you want the log file to be viewed (q to quit): "
          read ANS
          test "${ANS}" = "q" && break
        fi
        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
            else
              CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`
              get_logfile ${CFG}
              if test -n "${LOGF}"
              then
                echo
                echo "Found definition of log file: ${LOGF}"
                echo
                while test 1
                do
                  tput bold
                  echo -n "Do you want a continuous view (1) or an editor view (2) (q to quit) ? "
                  tput sgr0
                  read ANS
                  case "${ANS}"
                  in
                    1)
                      tail_log_colored ${LOGF}
                      disp_header
                      break
                      ;;
                    2)
                      select_logfile
                      break
                      ;;
                    q)
                      break 2
                      ;;
                    *)
                      tput cuu1;tput el
                      ;;
                  esac
                done
              else
                tput bold
                echo "Log file name cannot be extracted from the configuration file."
                echo "Please check syntax."
                tput sgr0
              fi
            fi
          else
            tput bold
            echo "Incorrect value, must be numeric."
            tput sgr0
          fi
        fi
      done
      ;;
    7)
      #---------------------------------------------------
      # Create/Edit guest stop script
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editstop
      ;;
    8)
      #---------------------------------------------------
      # Create/Edit guest pre-start script
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editprestart
      ;;
    9)
      #---------------------------------------------------
      # Create/Edit guest check/run script
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editchkrun
      ;;
    q)
      break
      ;;
  esac
done

exit
