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

#=============================================================================
# Function: Press_Enter
#=============================================================================
function Press_Enter
{
  echo
  echo -n "[44m[37mPress enter[0m"
  read ENTER
  tput cuu1;tput el
}

IS_SYSTEMD=0
which systemctl >/dev/null 2>&1 && IS_SYSTEMD=1
if test ${IS_SYSTEMD} = 0
then
  tput bold
  echo "Operating systems with 'systemd' only are supported."
  tput sgr0
  exit
fi

#--- Added for kit 1.58: preference file location has moved
PREFFILE=/opt/charon/utils/charon.preferences
if test -e /root/.charon.preferences
then
  mv -f /root/.charon.preferences ${PREFFILE}
fi

if test `id -u` -ne 0
then
  if test -n "`grep ^ENABLESUDO=1$ ${PREFFILE} 2>/dev/null`"
  then
    sudo $0
    exit
  fi
fi

#--- Check if 'atd' service is enabled
ATDX=0
systemctl -q is-enabled atd 2>/dev/null
if test $? -ne 0
then
  tput bold
  echo "'atd' service is not enabled. Please enable it."
  tput sgr0
  ATDX=1
fi

#--- Check if 'atd' service is enabled
systemctl -q is-active atd 2>/dev/null
if test $? -ne 0
then
  tput bold
  echo "'atd' service is not running. Please start it."
  tput sgr0
  ATDX=1
fi

test ${ATDX} -eq 1 && Press_Enter

export PERL5LIB=${PERL5LIB}:/opt/charon/utils
RUNMENU="./menu_mod.pl -menu=charon_menumain.dat"

crontab -l 2>/dev/null | grep -v '#' | grep -q charon_
if test $? -eq 0
then
  tput bold
  echo "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 '/etc/cron.d/charon' file."
else
  CHK=`ps -eo pid,command | grep -w perl | grep "${RUNMENU}$"`
  if test -z "${CHK}"
  then
    cd /opt/charon/utils
    export DBUS_SESSION_BUS_ADDRESS=
    ${RUNMENU}
    cd - >/dev/null
  else
    PID=`echo ${CHK} | awk '{print $1}'`
    STR=`ps -hp ${PID} -o start`
    TTY=`ps -hp ${PID} -o tty`
    tput bold
    echo "Another process is already running the 'menu' !"
    tput sgr0
    echo "Please disconnect this session first."
    echo "Pid: ${PID} on ${TTY}, started: ${STR}."
  fi
fi
exit
