#!/bin/bash
#-------------------------------------------------------------------------------
# charon_menu_cron
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2023 STROMASYS.
# All rights reserved.
# Products: AXP/VAX + PAR
#
# Parameter: $1 = empty (normal mode) or 
#            -setup = used for Toolkit installation (menusetup) or
#            -check = used when starting the 'menu' (upgrade case)
#set -x
VERSION=2.1

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

CHECKMODE=0
test "$1" = "-check" && CHECKMODE=1

get_preferences

function add_cron_expchk
{
  cat <<EOF >>${CRONFILE}
#
# Checks for license expiration: runs everyday at 09:00 with alert set to 15 days before expiration
0 9 * * * root /opt/charon/utils/charon_expchk 15
EOF

}

function add_cron_logevent
{
  cat <<EOF >>${CRONFILE}
#
# Log events report
* * * * * root /opt/charon/utils/charon_logevent
EOF
}

function add_cron_logarchive
{
  cat <<EOF >>${CRONFILE}
#
# Logs archiving utility (each Monday 00:00)
0 0 * * 1 root /opt/charon/utils/charon_logarchive -keep=60 -zip
EOF
}

function add_cron_cfglogmon
{
  cat <<EOF >>${CRONFILE}
#
# Configuration and log files monitoring (every 5 minutes by default)
*/5 * * * * root /opt/charon/utils/charon_cfglogmon
EOF
}

function add_cron_oomprotect
{
  cat <<EOF >>${CRONFILE}
#
# Protection against OOM killer for Charon license processes (every 15 minutes by default)
*/15 * * * * root /opt/charon/utils/charon_oomprotect
EOF
}


function check_crontab
{
  echo
  if test ! -e ${ETCCHARON}/CharonToolkit.cron.no.check
  then
    if test ${CHECKMODE} -eq 0
    then
      echo "[44m[37m Checking... [0m"
    else
      echo "Checking ${CRONFILE} file entries..."
    fi
    TMPF="/tmp/`basename $0`.$$"
    if test -e ${CRONFILE}
    then
      cp ${CRONFILE} ${TMPF}
    else
      touch ${TMPF}
    fi
    CHK=1
    for SC in `grep "^function add_cron_" $0 | sed "s=^function add_cron_==g"`
    do
      test ${CHECKMODE} -eq 0 && echo "Checking 'charon_${SC}' presence in crontab file..."
      LINEC=`grep ${CHARONDIR}/utils/charon_${SC} ${TMPF} | grep -v ^# | wc -l`
      if test ${LINEC} -le 1
      then
        LINE=`grep ${CHARONDIR}/utils/charon_${SC} ${TMPF}`
        if test -z "${LINE}"
        then
          echo "${FGORANGE}${CHARONDIR}/utils/charon_${SC} missing in crontab[0m -> ${FGBLUE}added[0m"
          add_cron_${SC}
          CHK=0
        else
          if test "`echo ${LINE} | cut -c1`" = "#"
          then
            if test ${LINEC} -eq 0
            then
              echo "${BGORANGE} WARNING [0m 'charon_${SC}' is commented/not executed in crontab "
            else
              echo "$(tput bold)Note$(tput sgr0): 'charon_${SC}' is executed and also commented in crontab "
            fi
          fi
        fi
      else
        echo "${BGORANGE} WARNING [0m ${CHARONDIR}/utils/charon_${SC} cannot be present more than once."
        CHK=0
      fi
    done
    rm -f ${TMPF}
    if test ${CHK} = 1
    then
      test ${CHECKMODE} -eq 0 && echo "[32mDone.[0m"
      return 0
    else
      if test ${CHECKMODE} -eq 0
      then
        echo
        echo "${BGORANGE} WARNING [0m"
        echo "${FGORANGE}Check failure, Charon recurring jobs need to be updated/verified...[0m"
      fi
      return 1
    fi
  fi
}

. `dirname $0`/charon_common

CRONTAB=/usr/bin/crontab
CRONFILE=/etc/cron.d/charon

if test ${CHECKMODE} -eq 0
then
  echo
  display_header "Manage recurring jobs (cron)"

  if test `id -u` -ne 0
  then
    echo "[31mERROR[0m: must be root !"
    Press_Enter
    exit 1
  fi
fi

systemctl -q is-active crond
if test $? -ne 0
then
  echo "${BGORANGE} WARNING $(tput sgr0)"
  echo "${FGORANGE}'crond' service is not active! Please enable and start the service.$(tput sgr0)"
  Press_Enter
  exit 2
fi

CRONWC=`wc -l ${CRONFILE} 2>/dev/null | awk '{print $1}'`
if test ${CRONWC:-0} -eq 0
then
  echo "${FGBLUEBOLD}Initializing crontab file ${CRONFILE}...[0m"
  cat <<EOF >${CRONFILE}
# Charon crontab
#------------------------------------------------------------------------------
# Syntax:
#
# *    *    *    *    *  <user> <command to execute>
# |    |    |    |    |
# |    |    |    |    |
# |    |    |    |    +----- day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names)
# |    |    |    +---------- month (1 - 12)
# |    |    +--------------- day of month (1 - 31)
# |    +-------------------- hour (0 - 23)
# +------------------------- min (0 - 59)
#
EOF

  grep "^function add_cron" $0 | awk '{print $2}' | while read F
  do
    ${F}
  done
  echo "Done."
  test -n "$1" && exit 0
else
  if test "$1" = "-setup"
  then
    echo "${FGBLUEBOLD}crontab file already exists, you will be prompted to update...[0m"
    sleep 2
  fi
fi

if test ${CHECKMODE} -eq 1
then
  check_crontab
  test $? = 0 || Press_Enter
  exit
fi

while test 1
do
  CHK=1
  JOBS=""
  for SC in `grep "^function add_cron_" $0 | sed "s=^function add_cron_==g"`
  do
    crontab -l 2>/dev/null | grep -v '#' | grep -q ${CHARONDIR}/utils/charon_${SC}
    if test $? -eq 0
    then
      CHK=0
      JOBS="${JOBS} ${CHARONDIR}/utils/charon_${SC}"
    fi
  done
  if test $CHK -eq 0
  then
    echo
    echo "${BGORANGE} WARNING $(tput sgr0)"
    echo "${FGORANGE}The recurring jobs in the toolkit are no more located in the root's crontab.$(tput sgr0)"
    echo "Please delete or comment the related entries (using 'crontab -e') and use the"
    echo "'Manage recurring jobs' option from the 'menu' to create these entries in"
    echo "the '${CRONFILE}' file."
    echo
    tput bold
    echo "Jobs to be commented/deleted:"
    tput sgr0
    echo ${JOBS} | tr " " "\n"
    echo
    while test 1
    do
      echo -n "Do you want to edit root's crontab now (y/n) ? "
      read ANS
      case "${ANS}"
      in
        y|Y)
          crontab -e
          display_header "Manage recurring jobs (cron)"
          break
          ;;
        n|N)
          break 2
          ;;
      esac
    done
  else
    break
  fi
done


#--- Ask editor. 'gvim' cannot be used / empty buffer
ask_editor nogvim
if test -n "${EDI}"
then
  while test 1
  do
    echo
    echo "Editing '${CRONFILE}'..."
    Press_Enter
    SAVEDI=${EDITOR}
    EDITOR=${EDI}
    export EDITOR
    if test -z "`echo ${EDI}|grep vim`"
    then
      ${EDI} ${CRONFILE} 2>/dev/null
    else
      ${EDI} -u ${CHARONDIR}/utils/charoncron.vimrc ${CRONFILE} 2>/dev/null
    fi
    EDITOR=${SAVEDI}
    export EDITOR
    systemctl reload crond

    check_crontab
    test $? = 0 && break
    Press_Enter
  done
fi

exit
