#!/bin/sh
#-------------------------------------------------------------------------------
# charon_expchk
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2022 STROMASYS.
# All rights reserved.
#
# Parameters:
#  - number of days before alert (optional, default = 7)
#  - '-nomail' : to prevent from sending an alert email (used to check key can be read)
#  - '-expdat=DD-Mmm-YYYY' : optional, expiration date forced (debug mode)
#
# Interface with monitoring utilities:
#  - create the /opt/charon/utils/charon_expchk.custom, make it executable and
#    use it with $1 = alert code, $2 = alert message
#-------------------------------------------------------------------------------
#
VERSION=1.30

for P in `ls /etc/profile.d/charon*`;do . $P;done

NBALTfile="/tmp/charon_expchk.nbalt$$.tmp"

#=============================================================================
# Function: run the custom alert script
#=============================================================================
function monitorsender
{
  # $1 = message code
  # $2 = message content
  if test -x ${MONITORCUS}
  then
    ${MONITORCUS} $1 "$2"
  fi
}

#=============================================================================
# Function: get usb bus number
#=============================================================================
function get_usbbusdev
{
  USBBUSDEV=`/usr/bin/lsusb|grep HASP|cut -f1 -d:|awk '{print $2"/"$4}'`
  TIM=`date +"%Y%m%d;%H%M%S"`
  echo "${TIM};USB_DEVICE;Bus/Dev ${USBBUSDEV}" >>${LOG}

  USBHCI=`/bin/dmesg | grep 'Vendor=0529,' | tail -1 | cut -f2 -d']' | cut -f1 -d: | sed "s=^ ==g"`
  USBHCIMODE=`/bin/dmesg | grep "${USBHCI}:" | grep hci_hcd | grep -w using | tail -1 | sed "s=\(^.* using \)\(.*$\)=\2=g"`
  echo "${TIM};USB_HCI;${USBHCI};${USBHCIMODE}" >>${LOG}
}

#=============================================================================
# Function: usb reset
#=============================================================================
function usb_daemons_reset
{
  if test -n "${USBHCIMODE}"
  then
    ls /sys/bus/pci/drivers/${USBHCIMODE} | grep : | while read L
    do
      test "${TERM}" != "dumb" && echo "Unbinding USB devices..."
      TIM=`date +"%Y%m%d;%H%M%S"`
      echo "${TIM};USB_UNBIND;Unbinding ${USBHCI}/${USBHCIMODE}/${L}" >>${LOG}
      echo ${L} >/sys/bus/pci/drivers/${USBHCIMODE}/unbind
      sleep 1
      test "${TERM}" != "dumb" && echo "Binding USB devices..."
      TIM=`date +"%Y%m%d;%H%M%S"`
      echo "${TIM};USB_BIND;Binding ${USBHCI}/${USBHCIMODE}/${L}" >>${LOG}
      echo ${L} >/sys/bus/pci/drivers/${USBHCIMODE}/bind
    done
  else
    TIM=`date +"%Y%m%d;%H%M%S"`
    test "${TERM}" != "dumb" && echo "Cannot Unbind, USBHCI variable is empty"
    echo "${TIM};USB_UNBIND;Cannot Unbind, USBHCI variable is empty" >>${LOG}
  fi
  echo "`date +'%Y%m%d;%H%M%S'`;aksusbd restart" >>${LOG}
  if test "${TERM}" != "dumb" 
  then 
    echo "Restarting aksusbd daemons..."
  else
    echo "Restarting aksusbd daemons..." >>${LOG}
  fi
  /usr/bin/systemctl restart aksusbd
}

#=============================================================================
# Function: display_licfound
#=============================================================================
function display_licfound
{
  echo "[1mLicenses found on this server[0m:"
  echo -n "- ${FGBLUE}USB dongles: "
  /usr/bin/lsusb -d 0529: 2>/dev/null | wc -l
  echo -n "[0m"
  if test "$1" = "full"
  then
    /usr/bin/lsusb -d 0529:0001 -v 2>/dev/null | grep -e ^Bus -e iProduct | sed "s=^=    =g"
  fi

  echo -n "- ${FGBLUE}Software licenses (SL): "
  ls ${SLREPO}/*.v2c 2>/dev/null | cut -f1 -d "_" | sort -u | wc -l
  echo -n "[0m"
  if test "$1" = "full"
  then
    for LIC in `ls ${SLREPO}/*_base.v2c 2>/dev/null`
    do
      LICID=`basename ${LIC} | cut -f1 -d "_"`
      echo -n "    License Id: ${LICID} "
      NBUPD=`ls ${SLREPO}/${LICID}_update*.v2c 2>/dev/null | wc -l`
      test ${NBUPD:-0} -eq 0 && echo || echo "(updates: ${NBUPD})"      
    done
  fi

  echo
}

#=============================================================================
# Function: reset number of alerts
#=============================================================================
function NBALT_reset
{
  echo 0 >${NBALTfile}
}

#=============================================================================
# Function: increment number of alerts
#=============================================================================
function NBALT_incr
{
  T=`cat ${NBALTfile} 2>/dev/null`
  test -z "$T" && T=0
  T=T+1
  echo $T >${NBALTfile}
}


#-----------------------------------------------------------------------------
# Main script
#-----------------------------------------------------------------------------
CHCOMMON=/opt/charon/utils/charon_common

if test -x ${CHCOMMON}
then
  . ${CHCOMMON}
else
  echo "ERROR: file ${CHCOMMON} is missing."
  echo "Cannot continue."
  monitorsender "FILENOTFND" "the ${CHCOMMON} file is missing or not executable."
  exit 1
fi
MONITORCUS=${CHARONDIR}/utils/`basename $0`.custom

EXPDAT=""
MSG=""
LVL="Informational"
LOG=/opt/charon/log/charon_expchk.log
NOLICENSEFLAG=/root/.charon.expchk.nodongle
DONGLESFILE="${CHARONDIR}/utils/charon_licenses.list"
ANSI_TO_HEX="FF2020 00D200 FFFF00 2020FF FF00FF 00FFFF C0C0C0"

SLREPO="/var/hasplm/installed/68704"

get_preferences
if test "${TERM}" != "dumb"
then
  display_header "License expiration check"
  echo
fi

if test `id -u` -ne 0
then
  if test "${TERM}" != "dumb"
  then
    tput bold
    echo "Must be root !"
    tput sgr0
    echo -n "[44m[37mPress enter[0m"
    read ENTER
    tput cuu1;tput el
  else
    echo "Must be root !"
  fi
  echo
  exit 1
fi

if test "${TERM}" != "dumb"
then
  #--- Check if 'atd' service is enabled
  CHK=0
  systemctl -q is-enabled atd 2>/dev/null
  if test $? -ne 0
  then
    tput bold
    echo "WARNING: 'atd' service is not enabled. Please enable it."
    tput sgr0
    CHK=2
  fi

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

  #--- Check if 'aksusbd' service is enabled
  systemctl -q is-enabled aksusbd 2>/dev/null
  if test $? -ne 0
  then
    tput bold
    echo "WARNING: 'aksusbd' service is not enabled. Please enable it."
    tput sgr0
    test ${CHK} -lt 3 && CHK=2
  fi

  #--- Check if 'aksusbd' service is active
  systemctl -q is-active aksusbd 2>/dev/null
  if test $? -ne 0
  then
    tput bold
    echo "ERROR: 'aksusbd' service is not running. Please start it."
    tput sgr0
    CHK=3
  fi

  if test ${CHK} -ne 0
  then
    echo
    tput sgr0
    echo -n "[44m[37mPress enter[0m"
    read ENTER
    tput cuu1;tput el
    exit ${CHK}
  fi
fi

OUTVIEW=/tmp/hasp_srm_view.check
echo >${OUTVIEW}

typeset -i N=0
typeset -i MAXTRY=3
typeset -i I=0
typeset -i MAXWAIT=30
NOMAIL=0
FORCEDEXPDAT=""
NBD=7

echo "`date +'%Y%m%d;%H%M%S'`;BEGIN" >>${LOG}
echo "`date +'%Y%m%d;%H%M%S'`;P1=$1" >>${LOG}
echo "`date +'%Y%m%d;%H%M%S'`;P2=$2" >>${LOG}
echo "`date +'%Y%m%d;%H%M%S'`;P3=$3" >>${LOG}

while test $# -ne 0
do
  case "$1"
  in
    -nomail)
      NOMAIL=1
      ;;
    -expdat=[0-9][0-9]-[A-Z][a-z][a-z]-[0-9][0-9][0-9][0-9])
      FORCEDEXPDAT=`echo $1|cut -f2 -d'='`
      ;;
    *)
      if test -z "`echo $1 | tr -d [:digit:]`"
      then
        NBD=$1
      else
        echo "WARNING: Invalid parameter '$1'. Skipping."
      fi
      ;;
  esac
  shift        
done


OPTHASP=""
HASPEXE=`which hasp_srm_view 2>/dev/null`
if test -z "${HASPEXE}"
then
  if test "${TERM}" != "dumb"
  then
    echo "Cannot find 'hasp_srm_view' executable file."
    echo "Please verify CHARON is installed and PATH is correctly set."
    echo
  fi
  monitorsender "FILENOTFND" "the hasp_srm_view executable file is missing or not executable."
  exit 1
else
  test -n "`strings ${HASPEXE} | grep ^-all`" && OPTHASP="-all"
fi

get_usbbusdev

test "${TERM}" != "dumb" && display_licfound


LICNUM="Unknown_License"
while test $N -lt ${MAXTRY}
do
  echo "`date +'%Y%m%d;%H%M%S'`;Running hasp_srm_view ${OPTHASP}" >>${LOG}
  if test "${TERM}" != "dumb"
  then
    echo -n "Please wait, reading the license key"
    test -z ${OPTHASP} && echo "." || echo "s."
    sleep 1
    tput cuu1;tput el
    echo -n "Please wait, generating output..."
    touch ${OUTVIEW}
    echo "hasp_srm_view ${OPTHASP} >${OUTVIEW} 2>&1" | at now >${OUTVIEW}.tmp 2>&1
    ATNUM=`grep ^job ${OUTVIEW}.tmp | awk '{print $2}'`
    rm -f ${OUTVIEW}.tmp
    typeset -i T=0
    while test 1
    do
      T=T+1
      sleep 2
      echo -n "."
      test -z "`at -l | grep -w ^${ATNUM}`" && break
      if test $T -gt 60
      then
        >${OUTVIEW}
        break
      fi
    done
    echo
    tput cuu1;tput el
  else
    hasp_srm_view ${OPTHASP} >${OUTVIEW}
  fi
  test -e ${OUTVIEW} && echo "`date +'%Y%m%d;%H%M%S'`;`ls -l ${OUTVIEW}`" >>${LOG}

  NBKEYS=`grep "Trying to connect to the key:" ${OUTVIEW} | wc -l`
  NBNOTFND=`grep "key not found" ${OUTVIEW} | wc -l`
  if test ${NBKEYS} -ne ${NBNOTFND} -a ${NBKEYS} -gt 0
  then
    LICNUM=`grep "^The License Number" ${OUTVIEW} | sed "s=\(^.*Number: \)\(.*\)\(.$\)=\2=g" | tr "\n" " "`
    test -z "${LICNUM}" && LICNUM="Unknown_License"
    OUTP="/tmp/`echo ${LICNUM} | tr ' ' '_'`.txt"
    cat ${OUTVIEW} | sed "s=\r==g" >${OUTP}
    rm -f ${OUTVIEW} 2>/dev/null
    break
  else
    N=N+1
    echo "`date +'%Y%m%d;%H%M%S'`;License key not found (${N}/${MAXTRY})" >>${LOG}
    test "${TERM}" != "dumb" && echo "License key not found. Restarting services and retrying (${N}/${MAXTRY})..."
    usb_daemons_reset
    test "${TERM}" != "dumb" && echo
    sleep 6
  fi
done

ALERTFLAG=/tmp/`basename $0`.alert.flag
PRODSFILE=/tmp/`basename $0`.prods.tmp
rm -f ${ALERTFLAG} ${PRODSFILE} 2>/dev/null

if test -z "${LICNUM}" -o "${LICNUM}" = "Unknown_License"
then
  if test "${TERM}" != "dumb"
  then
    tput bold
    echo "Cannot find license."
    tput sgr0
  fi
  MSG="License not found, cannot check expiration date. Expiration checks are disabled until license is available."
  LVL="MAJOR"
  echo "`date +'%Y%m%d;%H%M%S'`;${LVL};${MSG}" >>${LOG}
  if test -e ${NOLICENSEFLAG}
  then
    echo "`date +'%Y%m%d;%H%M%S'`;NO_ALERT;No license alert already sent, will be reactivated when license will be found" >>${LOG}
  else
    touch ${NOLICENSEFLAG}
    if test -x ${CHARONDIR}/utils/charon_check.alertcmd
    then
      echo "`date +'%Y%m%d;%H%M%S'`;ALERT;No license alert sent" >>${LOG}
      ${CHARONDIR}/utils/charon_check.alertcmd EXPCHK "Severity Level: ${LVL}" "${MSG}" "N/A" "N/A"
    else
      echo "`date +'%Y%m%d;%H%M%S'`;NO_ALERT;No alert script detected" >>${LOG}
    fi
  fi
  monitorsender "KEYNOTFND" "License not found or cannot be read, please check."
else
  rm -f ${NOLICENSEFLAG} 2>/dev/null

  if test "${TERM}" != "dumb"
  then
    echo "Product Name                                  Expiration          Vers. AlertLvl"
    if test "${SEMIGRAPH}" = "enabled"
    then
      tput smacs
      echo "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq qqqqqqqqqqqqqqqqqqq qqqqq qqqqqqqq"
      tput rmacs
    else
      echo "--------------------------------------------- ------------------- ----- --------"
    fi
  fi

  TODDAT=`date +%Y%m%d`
  PRDNAM=""
  LASTLIC=""
  LASTPRD=""

  MONITOREXPDAT=""
  TRYKEYID=""
  typeset -i NBLIC=0
  NBALT_reset
  RUNHOST=""
  grep -e "^The License" -e "CHARON Sentinel" -e "^Product Name" -e "^Released product" -e "^License expiration" -e "^License time" -e "or Version:" \
       -e "^Trying to connect to the key" -e "^Sentinel HASP key not found" -e "^License Manager running at host" ${OUTP} | while read LINE
  do
    case "`echo ${LINE} | awk '{print $1,$2}'`"
    in
      "Trying to")
        if test -n "`echo ${LINE} | grep '^Trying to connect to the key'`"
        then
          TRYKEYID=`echo ${LINE} | cut -f2 -d':' | tr -dc [:digit:]`
        fi
        ;;
      "License Manager")
        if test -n "`echo ${LINE} | grep '^License Manager running at host'`"
        then
          RUNHOST=`echo ${LINE} | cut -f2 -d':' | tr -d [:blank:] | tr -d [:cntrl:]`
        fi
        ;;
      "Sentinel HASP")
        if test -n "`echo ${LINE} | grep '^Sentinel HASP key not found'`"
        then
          if test -n "${TRYKEYID}"
          then
            NBSLFIL=`ls ${SLREPO}/${TRYKEYID}_*.v2c 2>/dev/null | wc -l`
            if test ${NBSLFIL} -gt 0
            then
              MSG="The Software License id ${TRYKEYID} may be in cloned state"
              LVL="MAJOR"
              monitorsender "CLONEDSL" "${MSG}. Please check!"

              COL="color='#000000' style='background-color:#FF8040'"
              touch ${ALERTFLAG}

              test "${TERM}" != "dumb" && echo
              T=`cat ${NBALTfile} 2>/dev/null`
              test $T = 0 && echo "No expired product found." >>${PRODSFILE}
              echo "<br>" >>${PRODSFILE}

              NBALT_incr
              echo "<hr color=#0A71B4>" >>${PRODSFILE}
              echo "<b>License id</b>: ${TRYKEYID} (Soft)<br>" >>${PRODSFILE}
              echo "This Software License may be in cloned state, severity <font ${COL}>&nbsp;${LVL}&nbsp;</font><br>" >>${PRODSFILE}

              if test "${TERM}" != "dumb"
              then
                echo "`tput bold`License id: ${TRYKEYID}`tput sgr0` (Soft)"
                echo -n "[35m"
                printf "%-65s %5s " "This Software License may be in cloned state!" ""
                echo "${LVL}[0m"
                echo
              fi
            fi
          fi
        fi
       ;;
      "CHARON Sentinel")
        if test "`echo ${LINE} | awk '{print $4}'`" = "SL"
        then
          LICHASPTYP="Software"
        else
          LICHASPTYP="USB"
        fi
        ;;
      "The License")
        case "`echo ${LINE} | awk '{print $3}'`"
        in
          "Number:")
            LASTPRD=""
            LICNUM=`echo ${LINE} | sed "s=\(^.*Number: \)\(.*\)=\2=g" | tr -d "\r\n"`
            NBALT_reset
            NBLIC=NBLIC+1
            LICDESC=`grep "^${LICNUM};" ${DONGLESFILE} 2>/dev/null | cut -f2 -d';'`
            COLDESC=`grep "^${LICNUM};" ${DONGLESFILE} 2>/dev/null | cut -f3 -d';'`
            COLHEX=`echo ${ANSI_TO_HEX} | cut -f${COLDESC} -d' ' 2>/dev/null`

            if test "${LICHASPTYP}" = "Software"
            then
              #-- No KeyId if Software license
              if test ${NBLIC} -gt 1
              then
                test "${TERM}" != "dumb" && echo
                T=`cat ${NBALTfile} 2>/dev/null`
                test $T = 0 && echo "No expired product found." >>${PRODSFILE}
                echo "<br>" >>${PRODSFILE}
              fi
              if test "${TERM}" != "dumb"
              then
                tput bold
                echo -n "License: ${LICNUM}"
                tput sgr0
                echo -n " (${LICHASPTYP})"
              fi
              echo "<hr color=#0A71B4>" >>${PRODSFILE}
              echo "<b>License</b>: ${LICNUM} (${LICHASPTYP})<br>" >>${PRODSFILE}
              if test -n "${LICDESC}"
              then
                if test "${TERM}" != "dumb"
                then
                  echo -n " [3${COLDESC:-0}m${LICDESC}[0m"
                fi
                echo "<b>Description</b>: <font color=#${COLHEX}>${LICDESC}</font><br>" >>${PRODSFILE}
              fi
              if test "${RUNHOST}" = "`hostname`"
              then
                echo 
                tput bold
                echo -n "Served by"
                tput sgr0
                echo -n ": ${FGBLUE}this host"
                tput sgr0
                echo "<b>Served by</b>: ${RUNHOST} (this host)<br>" >>${PRODSFILE}
              else
                echo 
                tput bold
                echo -n "Served by"
                tput sgr0
                echo -n ": ${RUNHOST}"
                echo "<b>Served by</b>: ${RUNHOST}<br>" >>${PRODSFILE}
              fi
              #echo "<br>" >>${PRODSFILE}
              test "${TERM}" != "dumb" && echo
            fi
            ;;
          "KeyId:")
            KEYID=`echo ${LINE} | sed "s=\(^.*KeyId: \)\(.*\)=\2=g" | tr "\r\n" " "`
            if test ${NBLIC} -gt 1
            then
              test "${TERM}" != "dumb" && echo
              T=`cat ${NBALTfile} 2>/dev/null`
              test $T = 0 && echo "No expired product found." >>${PRODSFILE}
              echo "<br>" >>${PRODSFILE}
            fi
            if test "${TERM}" != "dumb"
            then
              tput bold
              echo -n "License: ${LICNUM}"
              tput sgr0
              echo -n " (${LICHASPTYP}) KeyID: ${KEYID}"
            fi
            echo "<hr color=#0A71B4>" >>${PRODSFILE}
            echo "<b>License</b>: ${LICNUM} (${LICHASPTYP})<br>" >>${PRODSFILE}
            if test -n "${LICDESC}"
            then
              if test "${TERM}" != "dumb"
              then
                echo -n " [3${COLDESC:-0}m${LICDESC}[0m"
              fi
              echo "<b>Description</b>: <font color=#${COLHEX}>${LICDESC}</font><br>" >>${PRODSFILE}
            fi
            if test "${RUNHOST}" = "`hostname`"
            then
              echo
              tput bold
              echo -n "Served by"
              tput sgr0
              echo -n ": ${FGBLUE}this host."
              tput sgr0
              echo "<b>Served by</b>: ${RUNHOST} (this host)<br>" >>${PRODSFILE}
            else
              echo
              tput bold
              echo -n "Served by"
              tput sgr0
              echo -n ": ${RUNHOST}"
              echo "<b>Served by</b>: ${RUNHOST}<br>" >>${PRODSFILE}
            fi
            echo "<br>" >>${PRODSFILE}
            test "${TERM}" != "dumb" && echo
            ;;
        esac
        ;;
      "Major Version:")
        MAJVER=`echo ${LINE} | cut -f2 -d':' | tr -dc [:digit:]`
        ;;
      "Minor Version:")
        MINVER=`echo ${LINE} | cut -f2 -d':' | tr -dc [:digit:]`
        ;;
      "Product Name:")
        PRDNAM=`echo ${LINE} | sed "s=\(^.*Name: \)\(.*\)=\2=g" | tr -d "\r\n"`
        ;;
      "Released product"|"License expiration"|"License time")
        case "`echo ${LINE} | awk '{print $3}'`"
        in
          "expiration"|"date:")
            #--- Line example before build 18302:   "Released product expiration date: 05-Nov-2015"
            #--- Line example starting build 18302: "License expiration date: 20-Apr-2017 (slot number 2)"
            EXPDAT=`echo ${LINE} | cut -f2 -d: | cut -f1 -d '('`
            test -n "${FORCEDEXPDAT}" && EXPDAT=${FORCEDEXPDAT}
            EXPDAT=`echo ${EXPDAT} | sed "s= and = =g" | tr -d [:cntrl:]`
            MSG="License ${LICNUM}, Product: ${PRDNAM}, Expiration date: ${EXPDAT}"
            LVL="Informational"
            case "${EXPDAT}"
            in 
              "01-Jan-1970")
                EXPDAT="Unlimited"
                XPRDAT="99999999"
                ALTDAT="99999999"
                MAXDAT="99999999"
                MSG="License ${LICNUM}, Product: ${PRDNAM}, Expiration date: 01-Jan-1970 (Unlimited)"
                ;;
              "Unlimited")
                XPRDAT="99999999"
                ALTDAT="99999999"
                MAXDAT="99999999"
                MSG="License ${LICNUM}, Product: ${PRDNAM}, Expiration date: Unlimited"
                ;;
              "SL license not started yet")
                XPRDAT="99999999"
                ALTDAT="99999999"
                MSG="License ${LICNUM}, Product: ${PRDNAM}, Error: SL license not started yet"
                LVL="MAJOR"
                monitorsender "KEYNOTFND" "${MSG}"
                ;;
              *)
                XPRDAT=`date +%Y%m%d -d "${EXPDAT}"`
                ALTDAT=`date +%Y%m%d -d "${EXPDAT} -${NBD} days"`
                MAXDAT=`date +%Y%m%d -d "${EXPDAT} +2 days"`
                test -n "${FORCEDEXPDAT}" && MAXDAT="99999999"
                LVL="NEUTRAL"
                if test ${TODDAT} -ge ${XPRDAT}
                then
                  LVL="CRITICAL"
                  if test ${TODDAT} -eq ${XPRDAT}
                  then
                    if test -z "`echo ${PRDNAM} | grep 'CHARON-SSP'`"
                    then
                      #--- Case for CHARON-AXP and CHARON-VAX (no time in license output)
                      MSG="License ${LICNUM} expires today"
                    else
                      #--- Special case for CHARON-SSP: the license expires at 02:00 AM
                      if test `date +%H` -ge 2
                      then
                        LVL="EXPIRED"
                        MSG="License ${LICNUM} has expired"
                      else
                        MSG="License ${LICNUM} expires today"
                      fi
                    fi
                  else
                    LVL="EXPIRED"
                    MSG="License ${LICNUM} has expired"
                  fi
                else
                  if test ${TODDAT} -ge ${ALTDAT}
                  then
                    LVL="Informational"
                    MSG="License ${LICNUM} approaching termination, more than 7 days remaining"
                    for SD in CRITICAL:1 MAJOR:2 MAJOR:3 Minor:4 Minor:5 Minor:6 Minor:7
                    do 
                      TMPSEV=`echo ${SD} | cut -f1 -d':'`
                      TMPDAY=`echo ${SD} | cut -f2 -d':'`
                      ALT=`date +%Y%m%d -d "${EXPDAT} -${TMPDAY} days"`
                      if test "${TODDAT}" = "${ALT}"
                      then
                        LVL=${TMPSEV}            
                        MSG="License ${LICNUM} approaching termination, less than ${TMPDAY} day"
                        test ${TMPDAY} != 1 && MSG="${MSG}s"
                        MSG="${MSG} remaining"
                      fi
                    done
                  fi
                fi
                ;;
            esac
            if test "${TERM}" != "dumb"
            then
              case "${LVL}"
              in
                "Minor")    echo -n "${FGBLUE}";;
                "MAJOR")    echo -n "[35m";;
                "CRITICAL") echo -n "[31m";;
                "EXPIRED")  echo -n "[31m";;
              esac
              LVLDISP=${LVL}
              if test "${PRDNAM}" = "${LASTPRD}"
              then
                if test "${EXPDAT}" = "Unlimited"
                then
                  EXPDATDISP="with no date limit"
                  LVLDISP=""
                else
                  EXPDATDISP="& up to ${EXPDAT}"
                fi
                printf "%46s " ""
                printf "%-19s " "${EXPDATDISP}"
              else
                printf "%-45s %-19s %5s " "`echo ${PRDNAM}|cut -c1-45`" "${EXPDAT}" "${MAJVER}.${MINVER}"
              fi
              test "${LVLDISP}" = "EXPIRED" && echo -n "[41m[30m"
              test "${LVLDISP}" = "Informational" && LVLDISP="INFO"
              LVLDISP=`echo ${LVLDISP} | cut -c1-8`
              echo "${LVLDISP}[0m"
            fi
            echo "`date +'%Y%m%d;%H%M%S'`;LICNUM=${LICNUM:-UNKNOWN};LEVEL=${LVL};MESSAGE=${MSG};PRDNAM=${PRDNAM};EXPDAT=${EXPDAT}" >>${LOG}
            echo "`date +'%Y%m%d;%H%M%S'`;NBD=${NBD};MSG=${MSG}" >>${LOG}
            echo "`date +'%Y%m%d;%H%M%S'`;TODDAT=${TODDAT} (today), XPRDAT=${XPRDAT} (expir.),  ALTDAT=${ALTDAT} (alertdate), MAXDAT=${MAXDAT}" >>${LOG}
            test ${TODDAT} -ge ${XPRDAT} && echo "`date +'%Y%m%d;%H%M%S'`;TODDAT=${TODDAT} (today) ge XPRDAT=${XPRDAT} (expir.)" >>${LOG}
            test ${TODDAT} -ge ${ALTDAT} && echo "`date +'%Y%m%d;%H%M%S'`;TODDAT=${TODDAT} (today) ge ALTDAT=${ALTDAT} (alertdate)" >>${LOG}
            test ${TODDAT} -gt ${MAXDAT} && echo "`date +'%Y%m%d;%H%M%S'`;TODDAT=${TODDAT} (today) gt MAXTDAT=${MAXDAT} (no alert sent)" >>${LOG}
            if test -n "${MSG}"
            then
              MONITOREXPDAT=": ${EXPDAT}. License: ${LICNUM}. Product: ${PRDNAM}"
              if test ${TODDAT} -ge ${ALTDAT} -a ${TODDAT} -le ${MAXDAT}
              then
                case "${LVL}"
                in
                  Informational)   COL="color='#FFFFFF' style='background-color:#2020FF'";;
                  Minor)           COL="color='#FFFFFF' style='background-color:#800080'";;
                  MAJOR)           COL="color='#000000' style='background-color:#FF8040'";;
                  CRITICAL)        COL="color='#FFFFFF' style='background-color:#FF2020'";;
                  EXPIRED)         COL="color='#FF2020' style='background-color:#303030'";;
                  *)               COL="color='#000000'";;
                esac
                touch ${ALERTFLAG}
                NBALT_incr
                echo "<b>Product</b>: ${PRDNAM}, Expiration date: ${EXPDAT}, severity <font ${COL}>&nbsp;${LVL}&nbsp;</font><br>" >>${PRODSFILE}
              fi
              monitorsender "${LVL:-NEUTRAL}" "${MONITOREXPDAT}"
            fi
            ;;
          "time"|"remaining:")
            LASTPRD=${PRDNAM}
            LVL="NEUTRAL"

            #--- Line example before build 18302: "Released product time remaining: 5 hours and 40 minutes"
            #--- Line example starting build 18302: "License time remaining: 60 hours and 0 minutes (slot number 9)"
            EXPTIM=`echo ${LINE} | cut -f2 -d: | cut -f1 -d'(' | cut -c2- | tr -d [:cntrl:]`

            MONITOREXPDAT=": ${EXPTIM}. License: ${LICNUM}. Product: ${PRDNAM}"

            test -n "${FORCEDEXPDAT}" && EXPTIM=${FORCEDEXPDAT}
            MSG="License ${LICNUM}, Product: ${PRDNAM}, Time remaining: ${EXPTIM}"
            LVL="Informational"
            EXPHOUR=`echo ${EXPTIM} | awk '{print $1}'`
            EXPMINS=`echo ${EXPTIM} | awk '{print $4}'`
            if test ${EXPHOUR} -eq 0 -a ${EXPMINS} -eq 0
            then
              LVL="EXPIRED"
              MSG="License ${LICNUM} has expired"
            else
              test ${EXPHOUR} -lt 72 && LVL="Minor"
              test ${EXPHOUR} -lt 48 && LVL="MAJOR"
              test ${EXPHOUR} -lt 24 && LVL="CRITICAL"
              MSG="License ${LICNUM} approaching termination, ${EXPTIM} remaining"
            fi

            if test "${TERM}" != "dumb"
            then
              case "${LVL}"
              in
                "Minor")    echo -n "${FGBLUE}";;
                "MAJOR")    echo -n "[35m";;
                "CRITICAL") echo -n "[31m";;
                "EXPIRED")  echo -n "[31m";;
              esac
              EXPTIMS=`echo ${EXPTIM} | sed -e "s= and==g" -e "s=1 hours=1 hour=g" -e "s= minutes= min.=g"`
              printf "%-45s %-19s %5s " "`echo ${PRDNAM}|cut -c1-45`" "${EXPTIMS}" "${MAJVER}.${MINVER}"
              test "${LVL}" = "EXPIRED" && echo -n "[41m[30m"
              LVLDISP=`echo ${LVL} | cut -c1-8`
              test "${LVLDISP}" = "Informat" && LVLDISP="INFO"
              echo "${LVLDISP}[0m"
            fi

            echo "`date +'%Y%m%d;%H%M%S'`;LICNUM=${LICNUM:-UNKNOWN};LEVEL=${LVL};MESSAGE=${MSG};PRDNAM=${PRDNAM};EXPTIM=${EXPTIM}" >>${LOG}
            echo "`date +'%Y%m%d;%H%M%S'`;EXPHOUR=${EXPHOUR};MSG=${MSG}" >>${LOG}
            if test -n "${MSG}"
            then
              if test ${EXPHOUR} -le 96
              then
                case "${LVL}"
                in
                  Informational)  COL="color='#FFFFFF' style='background-color:#2020FF'";;
                  Minor)          COL="color='#FFFFFF' style='background-color:#800080'";;
                  MAJOR)          COL="color='#000000' style='background-color:#FF8040'";;
                  CRITICAL)       COL="color='#FFFFFF' style='background-color:#FF2020'";;
                  EXPIRED)        COL="color='#000000' style='background-color:#ff2020'";;
                  *)              COL="color='#000000'";;
                esac
                touch ${ALERTFLAG}
                NBALT_incr
                echo "<b>Product</b>: ${PRDNAM}, Time remaining: ${EXPTIM}, severity <font ${COL}>&nbsp;${LVL}&nbsp;</font><br>" >>${PRODSFILE}
              fi
              monitorsender "${LVL:-NEUTRAL}" "${MONITOREXPDAT}"
            fi
            ;;
        esac
        ;;
    esac
  done
  test "${TERM}" != "dumb" && echo
  T=`cat ${NBALTfile} 2>/dev/null`
  test $T = 0 && echo "No expired product found." >>${PRODSFILE}
  echo "<br>" >>${PRODSFILE}
fi

if test -e ${ALERTFLAG}
then
  if test "${NOMAIL}" = 0
  then
    if test -x ${CHARONDIR}/utils/charon_check.alertcmd
    then
      echo "`date +'%Y%m%d;%H%M%S'`;ALERT;Expiration alert sent" >>${LOG}
      ${CHARONDIR}/utils/charon_check.alertcmd EXPCHK "Alert requested ${NBD} days before expiration" "FILE:${PRODSFILE}"
      rm -f ${ALERTFLAG}
    else
      echo "`date +'%Y%m%d;%H%M%S'`;NO_ALERT;No alert script detected" >>${LOG}
    fi
  fi
fi

rm -f ${NBALTfile} 2>/dev/null

echo "`date +'%Y%m%d;%H%M%S'`;END" >>${LOG}

exit
