#!/bin/bash
#-------------------------------------------------------------------------------
# charon_menu_settings
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2023 STROMASYS.
# All rights reserved.
# Products: AXP/VAX + PAR
#set -x
VERSION=2.2

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

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

. `dirname $0`/charon_common
. `dirname $0`/charon_common_menu
LOGFLIST="${CHARONDIR}/utils/charon_logchk.list"
BOOTLIST="${CHARONDIR}/utils/charon_gstart.boot"
CHECKFORUPDATE="${ETCCHARON}/Check_for_updates.disabled"

#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
function oom_settings
{
  echo
  if test "${OOMPRVPIDKILL}" = "disabled"
  then
    OOMPRVPIDKILL="enabled"
    set_preferences
    echo
    echo "[32mCharon virtual machines will be protected against OOM Killer.[0m"
  else
    OOMPRVPIDKILL="disabled"
    set_preferences
    echo
    echo "[31mCharon virtual machines will not be protected against OOM Killer.[0m"
  fi
  echo
  tput smso
  echo " Applying and verifying changes for running guests... "
  tput rmso      
  display_guestslist
  Press_Enter
}

function manage_systemd_service
{
  # $1 = create, delete, start, stop, is-active
  # $2 = log name full path
  if test -s ${BOOTLIST}
  then
    rm -f /tmp/charon_menu_logchk.cfgbas.tmp 2>/dev/null
    grep -v ^# ${BOOTLIST} | while read LINE
    do
      EMU=`echo ${LINE} | cut -f1 -d';'`
      CFG=`echo ${LINE} | cut -f2 -d';'`
      get_logfile ${CFG}
      test "${LOGF}" = "$2" && basename ${CFG} | sed "s=\.cfg==g" >/tmp/charon_menu_logchk.cfgbas.tmp
    done
    CFGBAS=`cat /tmp/charon_menu_logchk.cfgbas.tmp 2>/dev/null`
    if test -n "${CFGBAS}"
    then
      case "$1"
      in
        "start")
          systemctl reset-failed charon_logmon_${CFGBAS}.service
          systemctl start        charon_logmon_${CFGBAS}.service
          ;;
        "stop")
          systemctl stop         charon_logmon_${CFGBAS}.service
          ;;
        "is-active")
          systemctl is-active charon_logmon_${CFGBAS}.service 2>/dev/null
          ;;
      esac
    else
      echo "[31mERROR:[0m Cannot $1 service. No managed guest associated with the log file"
      echo
      Press_Enter
    fi
  else
    echo "[31mERROR:[0m Cannot $1 service. No managed guest defined"
    echo
    Press_Enter
  fi
}

function global_logmon_settings
{
  echo
  if test "${GLOBALLOGMON}" = "enabled"
  then
    GLOBALLOGMON="disabled"
    set_preferences
    echo
    
    #--- Stop aksusbd monitoring
    if test -x /usr/sbin/aksusbd
    then
      if test "$(systemctl is-active charon_monusb.service 2>/dev/null)" = "active"
      then
        echo "Stopping aksusbd monitoring service..."
        systemctl stop charon_monusb.service 2>/dev/null
        echo
      fi
    fi

    #--- Stop hasp error.log file monitoring
    if test "$(systemctl is-active charon_monhasperrlog.service 2>/dev/null)" = "active"
    then
      echo "Stopping hasp error.log monitoring service..."
      systemctl stop charon_monhasperrlog.service 2>/dev/null
    fi

    #--- Stop VE license log file monitoring
    if test "$(systemctl is-active charon_monvesvrlog.service 2>/dev/null)" = "active"
    then
      echo "Stopping VE license log file monitoring service..."
      systemctl stop charon_monvesvrlog.service 2>/dev/null
    fi

    #--- Stop log monitoring for all virtual machines
    cat ${LOGFLIST} 2>/dev/null | while read RLOGF
    do
      echo
      SVC_IS_ACTIVE=`manage_systemd_service is-active ${RLOGF} | cut -f1 -d'-' | tr [:lower:] [:upper:]`
      if test "${SVC_IS_ACTIVE}" = "ACTIVE"
      then
        echo "Stopping log monitoring service for ${RLOGF}"
        manage_systemd_service stop ${RLOGF}
        sleep 1
      else
        echo "Log monitoring service for ${RLOGF} is not running. Skipped."
      fi
    done

  else
    GLOBALLOGMON="enabled"
    set_preferences
    echo

    #--- Start aksusbd monitoring
    if test "${MONAKSUSBDLOG}" = "enabled"
    then
      if test -x /usr/sbin/aksusbd
      then
        if test "$(systemctl is-active charon_monusb.service 2>/dev/null)" != "active"
        then
          echo "Starting aksusbd monitoring service..."
          systemctl start charon_monusb.service 2>/dev/null
          echo
        fi
      fi
    fi

    #--- Start hasp error.log file monitoring
    if test "${MONHASPERROR}" = "enabled"
    then
      if test "$(systemctl is-active charon_monhasperrlog.service 2>/dev/null)" != "active"
      then
        echo "Starting hasp error.log monitoring service..."
        systemctl start charon_monhasperrlog.service 2>/dev/null
      fi
    fi

    #--- Start VE license log file monitoring
    if test "${MONVELSLOG}" = "enabled"
    then
      if test "$(systemctl is-active charon_monvesvrlog.service 2>/dev/null)" != "active"
      then
        echo "Starting VE license log monitoring service..."
        systemctl start charon_monvesvrlog.service 2>/dev/null
      fi
    fi

    #--- Start log monitoring for all virtual machines
    cat ${LOGFLIST} 2>/dev/null | while read RLOGF
    do
      echo
      SVC_IS_ACTIVE=`manage_systemd_service is-active ${RLOGF} | cut -f1 -d'-' | tr [:lower:] [:upper:]`
      if test "${SVC_IS_ACTIVE}" != "ACTIVE"
      then
        echo "Starting log monitoring service for ${RLOGF}"
        manage_systemd_service start ${RLOGF}
        sleep 1
      else
        echo "Log monitoring service for ${RLOGF} is not running. Skipped."
      fi
    done

  fi
  echo
  Press_Enter
}

function set_charonguestservice
{
  echo
  echo "Default start timeout = [36m${SVCTIMOUTSTART} minutes[0m"
  while test 1
  do
    echo -n "Enter default timeout for start in minutes (greater than 0): "
    read ANS
    if test -n "${ANS}"
    then
      if test -n "`echo ${ANS} | tr -d [:digit:]`"
      then
        echo "Must be numeric (integer)."
      else
        if test ${ANS} -eq 0
        then
          echo "Must be greater than 0."
        else
          SVCTIMOUTSTART=${ANS}
          set_preferences
          break
        fi
      fi
    else
      echo "Not changed."
      break
    fi
  done

  echo
  echo "Default stop timeout = [36m${SVCTIMOUTSTOP} minutes[0m"
  while test 1
  do
    echo -n "Enter default timeout for stop in minutes (greater than 0): "
    read ANS
    if test -n "${ANS}"
    then
      if test -n "`echo ${ANS} | tr -d [:digit:]`"
      then
        echo "Must be numeric (integer)."
      else
        if test ${ANS} -eq 0
        then
          echo "Must be greater than 0."
        else
          SVCTIMOUTSTOP=${ANS}
          set_preferences
          break
        fi
      fi
    else
      echo "Not changed." 
      break
    fi
  done
}

function set_cfgfileupdatemon
{
  if test "${MONCFGFILEUPDATE}" = "enabled"
  then
    MONCFGFILEUPDATE="disabled"
  else
    MONCFGFILEUPDATE="enabled"
  fi
  set_preferences
}

function set_sesslogfilesizealert
{
  echo
  LASTMONSIZ=${MONLOGFILESIZE}
  while test 1
  do
    echo -n "Enter the limit in Mb (0=function disabled) [${LASTMONSIZ}]: "
    read ANS
    if test -z "${ANS}"
    then
      break
    else
      CHK=$(echo "${ANS}" | tr -d [:digit:])
      if test -n "${CHK}"
      then
        tput cuu1;tput el
      else
        MONLOGFILESIZE=$(printf "%d" ${ANS})
        set_preferences
        break
      fi
    fi
  done
}

function set_sesslogfileincralert
{
  echo
  LASTMONSIZ=${MONLOGFILEINCR}
  while test 1
  do
    echo -n "Enter the limit in Kb per hour (0=function disabled) [${LASTMONSIZ}]: "
    read ANS
    if test -z "${ANS}"
    then
      break
    else
      CHK=$(echo "${ANS}" | tr -d [:digit:])
      if test -n "${CHK}"
      then
        tput cuu1;tput el
      else
        MONLOGFILEINCR=$(printf "%d" ${ANS})
        set_preferences
        break
      fi
    fi
  done
}

function set_hasperrorlogmon
{
  if test "${GLOBALLOGMON}" = "enabled"
  then
    if test "${MONHASPERROR}" = "enabled"
    then
      MONHASPERROR="disabled"
      set_preferences
      test "$(systemctl is-active charon_monhasperrlog.service 2>/dev/null)" = "active" && systemctl stop charon_monhasperrlog.service 2>/dev/null
    else
      if test -s ${HASPLMINI}
      then
        if test "$(grep -w ^errorlog ${HASPLMINI} | cut -f2 -d'=' | tr -d [:space:])" = "1"
        then
          if test "$(grep -w ^rotatelogs ${HASPLMINI} | cut -f2 -d'=' | tr -d [:space:])" = "0"
          then
            MONHASPERROR="enabled"
            set_preferences
            test "$(systemctl is-enabled charon_monhasperrlog.service 2>/dev/null)" = "enabled" || systemctl enable charon_monhasperrlog.service 2>/dev/null
            test "$(systemctl is-active  charon_monhasperrlog.service 2>/dev/null)" = "active"  || systemctl start  charon_monhasperrlog.service 2>/dev/null
          else
            echo "[31m'Write Log Files Daily' is enabled in Sentinel ACC[0m"
            echo "Monitoring is not possible with rotating files. Please update using the"
            echo "menu option 'Sentinel Admin Control Center (firefox)' then 'Configuration'"
            echo "section."
            echo
            Press_Enter
          fi
        else
          echo "[31m'Write an Error Log File' is disabled in Sentinel ACC[0m"
          echo "Monitoring is not possible. Please update using the menu option"
          echo "'Sentinel Admin Control Center (firefox)' then 'Configuration' section."
          echo
          Press_Enter
        fi
      else
        echo "[31mNo Sentinel ACC configuration found, default options are used[0m"
        echo "Monitoring is not possible. Please update using the menu option"
        echo "'Sentinel Admin Control Center (firefox)' then 'Configuration' section."
        echo "Check the 'Write an Error Log File' box, let the 'Write Log Files Daily' box"
        echo "unchecked and define archiving/deletion options (recommended)."
        echo
        Press_Enter
      fi
    fi
  fi
}


#-----------------------------------------------------------------------------
# Main menu
#-----------------------------------------------------------------------------
while test 1
do
  display_header "Settings"
  if test `id -u` -ne 0
  then
    echo
    echo "[31mERROR[0m: must be root !"
    Press_Enter
    echo
    exit 1
  fi

  #--- get the user's preferences (function is in charon_common script)
  get_preferences

  #--- display the options
  echo " 1 - Out Of Memory (OOM) settings"
  echo -n "       Charon VM process killing prevention = "
  test "${OOMPRVPIDKILL}" = "enabled" && echo -n "[36m" || echo -n "[31m"
  echo "${OOMPRVPIDKILL}[0m"
  echo

  echo -n " 2 - Charon log monitoring (global): "
  test "${GLOBALLOGMON}" = "enabled" && echo -n "[36m" || echo -n "[31m"
  echo "${GLOBALLOGMON}[0m"
  echo

  echo " 3 - Charon virtual machine (guest) service default settings"
  echo "       Start timeout: [36m${SVCTIMOUTSTART} minutes[0m"
  echo "       Stop timeout:  [36m${SVCTIMOUTSTOP} minutes[0m"
  echo

  echo -n " 4 - Configuration file update time monitoring: "
  test "${MONCFGFILEUPDATE}" = "enabled" && echo -n "[36m" || echo -n "[31m"
  echo "${MONCFGFILEUPDATE}[0m"
  echo

  echo -n " 5 - Emulator log file size alert: "
  test "${MONLOGFILESIZE}" = "0" && echo "[31mdisabled[0m" || echo "[36m${MONLOGFILESIZE} Mb[0m"

  echo -n " 6 - Emulator log file increase alert: "
  test "${MONLOGFILEINCR}" = "0" && echo "[31mdisabled[0m" || echo "[36m${MONLOGFILEINCR} Kb[0m"
  echo

  echo -n " 7 - Charon Report automatic update check: "
  if test -e ${CHECKFORUPDATE}
  then
    echo "[31mdisabled[0m"
  else
    echo "[36menabled[0m"
  fi
  echo

  echo -n "${FGBLUEBOLD}Enter your choice ('q' to quit): [0m"
  read ANS
  case "${ANS}"
  in
    1)
      #--- OOM settings
      oom_settings
      ;;
    2)
      #--- Global log monitoring
      global_logmon_settings
      ;;
    3)
      #--- Charon guest service
      set_charonguestservice
      ;;
    4)
      #--- Configuration file update time monitoring
      set_cfgfileupdatemon
      ;;
    5)
      #--- Emulator log file size alert
      set_sesslogfilesizealert
      ;;
    6)
      #--- Emulator log file increase alert
      set_sesslogfileincralert
      ;;
    7)
      #--- Charon Report automatic check for update
      if test -e ${CHECKFORUPDATE}
      then
        rm -f ${CHECKFORUPDATE} 2>/dev/null
      else
        touch ${CHECKFORUPDATE}
      fi
      ;;
    q|Q)
      break
      ;;
  esac
done

exit
