#!/bin/sh
#-------------------------------------------------------------------------------
# setup (for license expiration check)
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2018 STROMASYS.
# All rights reserved.
#
#set -x
VERSION=1.2

if test "${PWD}" != "/opt/charon/utils"
then
  echo "Error: current directory is not set to '/opt/charon/utils'. Cannot continue."
  echo "The kit must be installed in this folder only."
  exit 1
fi

. `dirname $0`/charon_common
test -e /opt/charon/log || mkdir /opt/charon/log

#--- Convert old files to new ones (location changed)
test -e /etc/charon.d || mkdir /etc/charon.d
test -e ${CHARONDIR}/utils/charon_check.mailto     && mv -f ${CHARONDIR}/utils/charon_check.mailto     ${MAILTOFILE}
test -e ${CHARONDIR}/utils/charon_check.mailfrom   && mv -f ${CHARONDIR}/utils/charon_check.mailfrom   ${MAILFRFILE}
test -e ${CHARONDIR}/utils/charon_check.mailfooter && mv -f ${CHARONDIR}/utils/charon_check.mailfooter ${MAILFTFILE}
test -e /root/.charonmailmode                      && mv -f /root/.charonmailmode                      ${MAILMODEFILE}


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

function note_install_package
{
  tput smul
  echo -n "Note"
  tput rmul
  echo ": To install packages, use the command '# yum install <package>'. You can"
  echo "      also perform installation from the installation disc, 'Packages'"
  echo "      folder."
  echo
}

function set_mail_mode
{
  echo
  MAILMODE=`cat ${MAILMODEFILE} 2>/dev/null`
  test "${MAILMODE}" != "TEXT" && MAILMODE="HTML"
  case "${MAILMODE}"
  in
    "TEXT")
      echo HTML >${MAILMODEFILE}
      test $? = 0 && echo "Switched to HTML alerts" || echo "Failed to copy!"
      ;;
    "HTML")
      echo TEXT >${MAILMODEFILE}
      test $? = 0 && echo "Switched to TEXT alerts" || echo "Failed to copy!"
      ;;
  esac
}

function test_mail
{
  echo
  if test -e ${MAILTOFILE}
  then
    if test `grep -v ^# ${MAILTOFILE} | wc -l` -gt 0
    then
      while test 1
      do
        MAILTO=`grep -v ^# ${MAILTOFILE} | sort -u | tr "\n" ","|sed "s=,$==g"`
        echo -n "Do you want to send a test mail to ${MAILTO} (y/n) ? "
        read ANS
        echo
        case "${ANS}"
        in
          y)
            TM="${CHARONDIR}/utils/templates/TESTMAIL.mail"
            if test -s ${TM}
            then
              echo "Sending mail, please check your mailbox."
              ${CHARONDIR}/utils/charon_check.alertcmd TESTMAIL
            else
              tput bold
              echo "The test mail template does not exist. Please check"
              tput sgr0
              echo "Excepted file: ${TM}"
            fi
            sleep 2
            break
            ;;
          n)
            break
            ;;
          *)
            tput cuu1;tput el
            ;;
        esac
      done
    fi
  fi
}

function set_recipients_list
{
  echo
  tput bold;tput smul
  echo "Current list of recipients"
  tput rmul;tput sgr0
  if test `grep -v ^# ${MAILTOFILE} | wc -l` -eq 0
  then
    echo "Empty."
  else
    grep -v ^# ${MAILTOFILE}
  fi

  echo
  echo "Updating file using '`basename ${EDI}`'..."
  ${EDI} ${MAILTOFILE} 2>/dev/null
  >${MAILTOFILE}.tmp
  cat ${MAILTOFILE} | while read L
  do
    test -n "$L" && echo $L >>${MAILTOFILE}.tmp
  done
  mv -f ${MAILTOFILE}.tmp ${MAILTOFILE}
}

function display_setup_header
{
  display_header "Charon License expiration check setup"
}

display_setup_header

if test `id -u` -ne 0
then
  echo "[1m[31mRestriction: you must be root to continue.[0m"
  echo
  exit 1
fi

if test "${TERM}" = "vt100"
then
  cat <<EOF
Your current terminal is currently set to VT100. Using this mode you will
encounter erratic display (line drawing not correctly displayed)
The terminal must be set at least to vt200, xterm or dtterm.

[1m[36mPlease update the TERM value and restart the menu setup.[0m
EOF
  exit 1
fi

tput bold
echo "Mandatory executables and packages:"
tput sgr0
note_install_package
CHK=1

YUMINS=/tmp/menusetup.$$
yum list installed >${YUMINS}

for PE in P:at E:lsusb E:sendmail E:base64 P:bc
do
  P=`echo ${PE} | cut -f2 -d':'`
  case `echo ${PE} | cut -f1 -d':'`
  in
    "P")
      echo -n "- Package '${P}': "
      if test -n "`grep ^${P}\\. ${YUMINS}`"
      then
        echo "installed."
      else
        echo "[31m[1mnot installed![0m."
        CHK=0
      fi
      ;;
    "E")
      if test -z "`which ${P} 2>/dev/null`"
      then
        echo "- Executable '${P}': [31m[1mnot present![0m."
        CHK=0
      fi
      ;;
  esac
done
if test ${CHK} = 0
then
  echo "[1mPlease install the missing mandatory tools and restart the menu setup.[0m"
  exit 1
fi

rm -f ${YUMINS} 2>/dev/null
Press_Enter

display_setup_header
echo

CRONTAB=/usr/bin/crontab
CRONFILE=/var/spool/cron/`whoami`
CRONWC=`wc -l ${CRONFILE} 2>/dev/null | awk '{print $1}'`
if test ${CRONWC:-0} -eq 0
then
  echo "[1mInitializing crontab...[0m"
  cat <<EOFi >${CRONFILE}
# `whoami` crontab
#------------------------------------------------------------------------------
# Syntax:
#
# *    *    *    *    *  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)
#
EOFi
fi

if test -z "`grep -w charon_expchk ${CRONFILE}`"
then
  echo "Adding license expiration entries in the crontab..."
  cat <<EOFx >>${CRONFILE}
#
# Checks for license expiration: runs everyday at 01:00 and 09:00 with alert set
# to 15 days before expiration
0 1 * * * /opt/charon/utils/charon_expchk 15
0 9 * * * /opt/charon/utils/charon_expchk 15
EOFx
else
  echo "Entries in the crontab already exist for license expiration check."
  echo "Please update the crontab file manually using the '# crontab -e' command."
fi
echo
crontab -l | grep -w charon_expchk
Press_Enter

EDI="/usr/bin/vim"

display_setup_header
echo
echo "Please specify the recipients list if an alert has to be sent (using the vim"
echo "editor)."
echo
echo "Important note: one recipient per line."
sleep 3

if test ! -e ${MAILTOFILE}
then
  cat >${MAILTOFILE} <<EOFm
#---------------------------------------------------------------
# CHARON alertcmd mail recipients list / one recipient per line
#---------------------------------------------------------------
EOFm
fi

set_recipients_list

MAILMODE=`cat ${MAILMODEFILE} 2>/dev/null`
if test -z "${MAILMODE}"
then
  MAILMODE="HTML"
  echo "${MAILMODE}" >${MAILMODEFILE}
fi
display_setup_header
echo
echo -n "Current mail mode is set to : "
test "${MAILMODE}" = "HTML" && echo -n "[36m"
echo "${MAILMODE}[0m"
echo "It can be either TEXT or HTML."
echo
while test 1
do
  echo -n "Do you want to change it (y/n) ? "
  read ANS
  case "${ANS}"
  in
    y|Y)
      set_mail_mode
      break
      ;;
    n|N)
      break
      ;;
    *)
      tput cuu1
      tput el
      ;;
  esac
done

test_mail

echo
tput bold
echo "To check the script is working you can run the following command:"
tput sgr0
echo
echo "# /opt/charon/utils/charon_expchk"
echo
echo "It is possible to force an alert by specifying the -expdat parameter:"
echo -n "# /opt/charon/utils/charon_expchk -expdat="
date +"%d-%b-%Y"
echo
echo "Done."

exit
