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

. `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"
SVCNAME="charon_gstart"
MONLOG="${CHARONDIR}/log/charon_gstart.log"
TAILCMD=`grep ^TAILCMD= ${CHARONDIR}/utils/charon_logchk 2>/dev/null | cut -f2 -d'=' | tr -d '"'`

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 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 ! -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
}

#--------------------------------------------------------------------
# Check emulators path / following CHARON-AXP V4.6 location change
#--------------------------------------------------------------------
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
      GEXEBAS=`basename ${GEXE}`
      GEXENEW=`find ${CHARONDIR} -name ${GEXEBAS} -executable 2>/dev/null`
      test -n "${GEXENEW}" && GEXE=${GEXENEW}
      echo "${GEXE};${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
    tput bold
    echo "Must be root !"
    tput sgr0
    Press_Enter
    echo
    exit 1
  fi

  if test -n "`/sbin/chkconfig --list 2>/dev/null | grep ^charon_`"
  then
    cat <<EOF
[41m[30m WARNING [0m
CHARON services using the /etc/rc[0-6].d directory hierarchy have been found.
Starting with Kit41, Linux systems using 'systemd' are taken into account and
then services must be reinstalled.
Please:
1- Stop all running emulators
2- Execute the following commands:
`/sbin/chkconfig --list 2>/dev/null | grep ^charon_ | awk '{print $1}' | xargs -i echo "   # chkconfig --del {}"`
   # cd /opt/charon/utils
   # mv charon_gstart.boot charon_gstart.boot.sav
   # mv charon_logchk.list charon_logchk.list.sav

3 - Reboot your Linux server
4 - Once rebooted, you can add the virtual machines based on content found in 
    '/opt/charon/utils/charon_gstart.boot.sav' file

[44m[37m NOTE [0m
Common guest stop (shutdown) script is not affected unless you change the
configuration files location.

EOF
    echo
    exit 2
  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 - Manage 'systemd' services
2 - Start/stop guests               7 - View latest guest log file
3 - Connect to guest console        8 - Create/Edit guest stop script
4 - Connect to Remote Mgt Console   9 - Create/Edit guest pre-start script
5 - Edit configuration files        10- Create/Edit guest check/run script

EOF
    echo -n "${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
        echo
        display_guestslist -num
        echo
        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
            #---------------------------------------------------
            while test 1
            do
              echo
              tput bold
              echo "${FGBLUE}Available emulated hardware[0m"
              tput sgr0
              display_hr
              find ${CHARONDIR}/bin -type l | sort | while read LINE
              do
                printf "`basename ${LINE}` "
              done
              echo
              echo
              echo "Select virtual HW model, license conditionned"
              printf "(v to view HW on license key, q to quit): "
              read G_VHW
              case "${G_VHW}"
              in
                v)
                  echo
                  echo -n "Gathering license information, please wait..."
                  OUTVIEW=/tmp/charon_menu_gstart.tmp
                  hasp_srm_view >${OUTVIEW}
                  # if test -n "`grep 'key not found' ${OUTVIEW}`"
                  if test -z "`grep 'License type:' ${OUTVIEW}`"
                  then
                    touch ${OUTVIEW}
                    echo "hasp_srm_view >${OUTVIEW} 2>&1" | at now >${OUTVIEW}.tmp 2>&1
                    ATNUM=`grep ^job ${OUTVIEW}.tmp | awk '{print $2}'`
                    rm -f ${OUTVIEW}.tmp
                    typeset -i N=0
                    while test 1
                    do
                      N=N+1
                      sleep 2
                      echo -n "."
                      test -z "`at -l | grep -w ^${ATNUM}`" && break
                      if test $N -gt 30
                      then
                        >${OUTVIEW}
                        break
                      fi
                    done
                  fi
                  echo
                  tput cuu1;tput el
                  # if test -z "`grep 'key not found' ${OUTVIEW}`"
                  if test -n "`grep 'License type:' ${OUTVIEW}`"
                  then
                    tput bold
                    echo "${FGBLUE}Virtual HW found on license key[0m"
                    tput sgr0
                    display_hr
                    for LHW in `grep ^Virtual ${OUTVIEW} | sed -e "s=^Virtual.*: ==g" -e "s=, = =g" -e "s=AlphaServer_==g" | tr [:cntrl:] " "`
                    do
                      LHW=`echo ${LHW} | tr [:upper:] [:lower:]`
                      test -z "`echo ${LHW} | cut -c1 | tr -d [0123456789]`" && printf "as"
                      printf "${LHW} "                       
                    done
                    echo
                  else
                    tput bold
                    echo "License key not found !"
                    tput sgr0
                  fi
                  ;;
                q)
                  break
                  ;;
                *)
                  GUEST_EXE=`find ${CHARONDIR}/bin -type l -name ${G_VHW} 2>/dev/null`
                  if test -n "${GUEST_EXE}"
                  then
                    VER=`strings ${GUEST_EXE} | grep ^CHARON | grep Version | sed "s= (\%s)==g"`
                    echo
                    echo "Virtual Hardware selected: ${FGBLUE}${VER}[0m"

                    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)
                          #TODO(low): display to review, enhance: columns, limit to selected model ${G_VHW} ?
                          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
                          ;;
                        *)
                          if test -e ${CH}
                          then
                            CHK=`grep -e ";${CH}$" -e ";${CH};" ${BOOTLIST}`
                            if test -z "${CHK}"
                            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}

                              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
                                SVC_DESCRI="CHARON `basename ${GUEST_EXE}`/${GUEST_CFGBAS}"
                                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_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)
                                      test ${REEDIT} = 0 && ask_editor noquit
                                      REEDIT=0
                                      if test -n "${EDI}"
                                      then
                                        while test 1
                                        do
                                          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
                                          CFG=${GUEST_CFG}

                                          CHK=`grep -v ^# ${CFG} | grep -w load | grep -w virtual_serial_line | grep OPA`
                                          test -z "${CHK}" -a ${INSBLD} -ge 19103 && CHK=`grep -v ^# ${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"`
                                          if test -n "${PORT}"
                                          then
                                            echo "Console port correctly set to: ${PORT}"
                                          else
                                            tput bold
                                            echo "Console port not found. Please correct the configuration file."
                                            tput sgr0
                                          fi

                                          get_logfile ${CFG}
                                          echo "Log file is set to: ${FGBLUE}${LOGF}[0m"
                                          if test -z "`echo ${LOGF} | grep '/'`"
                                          then
                                            echo
                                            echo "[41m[37m ERROR [0m The full path is not specified."
                                            echo "        Please update the configuration file."
                                            Press_Enter
                                          else
                                            CHKD=`dirname ${LOGF}`
                                            if test ! -d ${CHKD}
                                            then
                                              echo "Making directory ${CHKD} ..."
                                              mkdir -p ${CHKD}
                                            fi
                                            break
                                          fi
                                        done
                                        echo

                                        test "${GLOBALLOGMON}" = "enabled" && create_logmon_service
                                        echo

                                        check_vdisk_files ${CFG} display
                                        echo

                                        check_network_settings ${CFG} display
                                      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)
                                            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
                                              echo "Restarting aksusbd log monitor service..."
                                              systemctl restart charon_monusb.service
                                            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
                                            ;;
                                          n)
                                            REEDIT=0
                                            break
                                            ;;
                                          e)
                                            REEDIT=1
                                            break
                                            ;;
                                          *)
                                            tput cuu1;tput el
                                            ;;
                                        esac
                                      done
                                      test ${REEDIT} = 0 && break
                                      ;;
                                    n)
                                      break
                                      ;;
                                    *)
                                      tput cuu1;tput el
                                      ;;
                                  esac
                                done
                              else
                                tput bold
                                echo "Failed to add guest."
                                tput sgr0
                              fi
                              break
                            else
                              tput bold
                              echo "Configuration file already exists in guest list, cannot be added!"
                              tput sgr0
                            fi
                          else
                            tput bold
                            echo "File does not exist, it is highly recommended to use the clone option"
                            tput sgr0
                          fi
                          ;;
                      esac
                    done
                  else
                    tput bold
                    echo "Invalid choice."
                    tput bold
                  fi
                  ;;
              esac
            done
            ;;         
          2)
            #---------------------------------------------------
            # Remove guest
            #---------------------------------------------------
            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 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 "${GUEST_EXE} -d ${GUEST_CFG}" | grep -v grep`
                          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"`
                          systemctl disable charon_${GUEST_CFGBAS}.service 
                          rm -f /etc/systemd/system/charon_${GUEST_CFGBAS}.service
                          systemctl daemon-reload

                          get_logfile ${GUEST_CFG}
                          if test -n "${LOGF}"
                          then
                            if test -n "`grep ^${LOGF}$ ${LOGFLIST} 2>/dev/null`"
                            then
                              while test 1
                              do
                                tput bold
                                echo -n "Do you want to remove the log monitoring service (y/n) ? "
                                tput sgr0
                                read ANS
                                case "${ANS}"
                                in
                                  y|Y)
                                    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
                                    echo
                                    break
                                    ;;
                                  n|N)
                                    echo
                                    break
                                    ;;
                                  *)
                                    tput cuu1;tput el
                                    ;;
                                esac
                              done
                            fi
                          fi
                          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="[30m"
                    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 "${GUEST_EXE} -d ${GUEST_CFG}" | grep -v grep`
                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 "[46m[30m[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)
      #---------------------------------------------------
      # Connect to Remote Management Console
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_rmc
      ;;
    5)
      #---------------------------------------------------
      # Edit configuration files
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editcfg
      ;;
    6)
      #-------------------------------------------------------
      # 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 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
      ;;
    7)
      #---------------------------------------------------
      # 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
      ;;
    8)
      #---------------------------------------------------
      # Create/Edit guest stop script
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editstop
      ;;
    9)
      #---------------------------------------------------
      # Create/Edit guest pre-start script
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editprestart
      ;;
    10)
      #---------------------------------------------------
      # Create/Edit guest check/run script
      #---------------------------------------------------
      ${CHARONDIR}/utils/charon_menu_editchkrun
      ;;
    q)
      break
      ;;
  esac
done

exit
