#!/bin/bash
#-------------------------------------------------------------------------------
# charon_expchk
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2023 STROMASYS.
# All rights reserved.
# Products: Charon-AXP/VAX + PAR + SSP
#
# 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 for debugging (example: 30-Oct-2022)
#  - '-hoursleft=h' : optional, number of hours remaining in a time limited license for
#                     debugging
#
# 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=2.6

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

NBALTfile="/tmp/charon_expchk.nbalt$$.tmp"
test -z "${FGORANGE}" && FGORANGE="[38;5;208m"

test -z "${CHARONDIR}" && CHARONDIR=/opt/charon
test ! -e ${CHARONDIR}/log && mkdir -p ${CHARONDIR}/log

#=============================================================================
# Function: Usage
#=============================================================================
function Usage
{
  cat <<EOF
  This script check for Charon license expiration and can send an email or
  execute a custom script.
  
  $(tput bold)Note$(tput sgr0):
    It must be executed as root.

  $(tput bold)Parameters$(tput sgr0):
    -h or --help        : display this help text
    any number          : defines the number of days before expiration when
                          alerts will start to be sent. Default = 7 days
    -expdat=dd-Mmm-YYYY : force the license expiration date to the specified
                          date (used for testing alerts). Date must be in
                          en_US format
                          Example: -expdat=25-Dec-2022
    -hoursleft=n        : force the hours left on a backup license that is
                          limited in time (used for testing alerts)
                          Example: -hoursleft=15
    -nomail             : prevents from executing the 
                          /opt/charon/utils/charon_check.alertcmd script used
                          to send the alert email

   $(tput bold)Use of custom script$(tput sgr0):
    Create the /opt/charon/utils/charon_expchk.custom script, make it
    executable and use it with $1 = alert code, $2 = alert message
    Alert code can be: FILENOTFND, KEYNOTFND, CLONEDSL, NEUTRAL, Informational,
    Minor, MAJOR, CRITICAL or EXPIRED

EOF
  exit 0
}

#=============================================================================
# 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 service..."
  else
    echo "Restarting aksusbd service..." >>${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}
}

#=============================================================================
# Function: check cloud license content
#=============================================================================
function compute_cloud_license
{
  test -n "${FORCEDEXPDAT}" && EXPDAT="${FORCEDEXPDAT} 00:00"
  test -n "${FORCEDHOURSLEFT}" && EXPDAT="${FORCEDHOURSLEFT} hour(s)"

  LVL="Informational"
  if test -z "$(echo "${EXPDAT}" | grep 'hour')"
  then
    #--- Date limited license
    #    Example: Expiration Date: 2021-12-22 23:55:00
    EXPDAT=$(date +"%d-%b-%Y %H:%M" -d "${EXPDAT}")

    MSG="License id ${LICID}, Product ${PRDNAM}, Expiration date: ${EXPDAT}"
    LVL="Informational"
    case "${EXPDAT}"
    in 
      "Unlimited")
        XPRDAT="999999999999"
        ALTDAT="999999999999"
        MAXDAT="999999999999"
        MSG="License id ${LICID}, Product ${PRDNAM}, Expiration date: Unlimited"
        ;;
      *)
        XPRDAT=$(date +%Y%m%d%H%M -d "${EXPDAT}")
        ALTDAT=$(date +%Y%m%d%H%M -d "$(echo ${EXPDAT} | awk '{print $1}') -${NBD} days")
        MAXDAT=$(date +%Y%m%d%H%M -d "$(echo ${EXPDAT} | awk '{print $1}') +2 days")
        test -n "${FORCEDEXPDAT}" && MAXDAT="999999999999"
        LVL="NEUTRAL"
        if test ${TODDAT} -ge ${XPRDAT}
        then
          LVL="EXPIRED"
          MSG="License id ${LICID}, Product ${PRDNAM}: expired"
        else
          if test ${TODDAT} -ge ${ALTDAT}
          then
            LVL="Informational"
            #MSG="License id ${LICID}, Product ${PRDNAM}: approaching termination, more than 7 days remaining"
            MSG="License id ${LICID}, Product ${PRDNAM}: approaching termination"
            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 "$(echo ${EXPDAT} | awk '{print $1}') -${TMPDAY} days")
              if test $(echo ${TODDAT} | cut -c1-8) -eq ${ALT}
              then
                LVL=${TMPSEV}            
                #MSG="License id ${LICID}, Product ${PRDNAM}: approaching termination, less than ${TMPDAY} day"
                MSG="License id ${LICID}, Product ${PRDNAM}: approaching termination"
                #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 "${FGORANGE}";;
        "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
        if test -n "${MAJVER}"
        then
          printf "%-45s %-19s %5s " "$(echo ${PRDNAM}|cut -c1-45)" "${EXPDAT}" "${MAJVER}.${MINVER}"
        else
          printf "%-45s %-19s %5s " "$(echo ${PRDNAM}|cut -c1-45)" "${EXPDAT}" " "
        fi
      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');CLOUD LICID=${LICID:-UNKNOWN};LEVEL=${LVL};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}
    if test ${TODDAT} -ge ${XPRDAT}
    then
      echo "$(date +'%Y%m%d;%H%M%S');TODDAT=${TODDAT} (today) ge XPRDAT=${XPRDAT} (expir.)" >>${LOG}
    else
      if test ${TODDAT} -ge ${ALTDAT}
      then
        echo "$(date +'%Y%m%d;%H%M%S');TODDAT=${TODDAT} (today) ge ALTDAT=${ALTDAT} (alertdate)" >>${LOG}
      else
        test ${TODDAT} -gt ${MAXDAT} && echo "$(date +'%Y%m%d;%H%M%S');TODDAT=${TODDAT} (today) gt MAXTDAT=${MAXDAT} (no alert sent)" >>${LOG}
      fi
    fi
    if test -n "${MSG}"
    then
      MONITOREXPDAT=": ${EXPDAT}. LicenseID: ${LICID}. Product: ${PRDNAM}"
      if test ${TODDAT} -ge ${ALTDAT} -a ${TODDAT} -le ${MAXDAT}
      then
        case "${LVL}"
        in
          Informational)   COL="SEVinfo";;
          Minor)           COL="SEVminor";;
          MAJOR)           COL="SEVmajor";;
          CRITICAL)        COL="SEVcritical";;
          EXPIRED)         COL="SEVexpired";;
          *)               COL="SEVdefault";;
        esac
        echo "${NBD} days" >${ALERTFLAG}
        NBALT_incr
        DREM=$(( ($(date -d ${EXPDAT} +%s) - $(date -d ${TODDAT} +%s)) / 86400 ))
        if test ${DREM} -ge 0
        then
          echo "<b>Product</b>: ${PRDNAM}, Expiration date: ${EXPDAT} (${DREM} days remaining), severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}
        else
          DREM=${DREM#-}
          echo "<b>Product</b>: ${PRDNAM}, Expiration date: ${EXPDAT} (${DREM} days ago), severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}
        fi
      else
        if test "${LVL}" = "EXPIRED"
        then
          DREM=$(( ($(date -d ${EXPDAT} +%s) - $(date -d ${TODDAT} +%s)) / 86400 ))
          DREM=${DREM#-}
          echo "<b>Product</b>: ${PRDNAM}, Expiration date: ${EXPDAT} (${DREM} days ago), severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}
        fi
      fi
      monitorsender "${LVL:-NEUTRAL}" "${MONITOREXPDAT}"
    fi
  else
    #--- Hour limited license
    #    Example: Expiration Date: 240 hour(s)
    EXPTIM=$(echo ${EXPDAT} | awk '{print $1}')

    MSG="License id ${LICID}, Product ${PRDNAM}, Time remaining: ${EXPTIM}"
    LVL="Informational"
    EXPHOUR=$(echo ${EXPTIM} | awk '{print $1}')
    if test ${EXPHOUR} -eq 0
    then
      LVL="EXPIRED"
      MSG="License id ${LICID}, Product ${PRDNAM}: expired"
    else
      test ${EXPHOUR} -lt 72 && LVL="Minor"
      test ${EXPHOUR} -lt 48 && LVL="MAJOR"
      test ${EXPHOUR} -lt 24 && LVL="CRITICAL"
      MSG="License id ${LICID}, Product ${PRDNAM}: ${EXPTIM} hour(s) remaining"
    fi

    if test "${TERM}" != "dumb"
    then
      case "${LVL}"
      in
        "Minor")    echo -n "${FGBLUE}";;
        "MAJOR")    echo -n "${FGORANGE}";;
        "CRITICAL") echo -n "[31m";;
        "EXPIRED")  echo -n "[31m";;
      esac
      EXPTIMS=$(echo ${EXPDAT} | sed -e "s= and==g" -e "s=1 hours=1 hour=g" -e "s= minutes= min.=g")
      if test -n "${MAJVER}"
      then
        printf "%-45s %-19s %5s " "$(echo ${PRDNAM}|cut -c1-45)" "${EXPTIMS}" "${MAJVER}.${MINVER}"
      else
        printf "%-45s %-19s %5s " "$(echo ${PRDNAM}|cut -c1-45)" "${EXPTIMS}" " "
      fi

      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');CLOUD LICID=${LICID:-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="SEVinfo";;
          Minor)           COL="SEVminor";;
          MAJOR)           COL="SEVmajor";;
          CRITICAL)        COL="SEVcritical";;
          EXPIRED)         COL="SEVexpired";;
          *)               COL="SEVdefault";;
        esac
        echo "96 hours" >${ALERTFLAG}
        NBALT_incr
        echo "<b>Product</b>: ${PRDNAM}, Time remaining: ${EXPTIM}, severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}
      fi
      monitorsender "${LVL:-NEUTRAL}" "${MONITOREXPDAT}"
    fi
  fi
}

function check_cloud_license
{
  OUTVIEW=/tmp/license_viewer.check
  echo >${OUTVIEW}

  typeset -i N=0
  typeset -i MAXTRY=3
  typeset -i I=0
  typeset -i MAXWAIT=30

  /opt/license-server/license_viewer >${OUTVIEW} 2>&1
  if test $? -eq 0
  then
    if test -z "$(grep 'Failed to retrieve the license' ${OUTVIEW})"
    then
      if test "${TERM}" != "dumb"
      then
        test -n "${FORCEDEXPDAT}" && echo "$(tput bold)Forced expiration date:$(tput sgr0) ${FORCEDEXPDAT}"
        test -n "${FORCEDHOURSLEFT}" && echo "$(tput bold)Forced hours left:$(tput sgr0) ${FORCEDHOURSLEFT}"
        test -n "${FORCEDEXPDAT}" -o -n "${FORCEDHOURSLEFT}" && echo
        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%H%M)
      PRDNAM=""
      LASTLIC=""
      LASTPRD=""

      MONITOREXPDAT=""
      TRYKEYID=""
      typeset -i NBLIC=0
      NBALT_reset
      RUNHOST=""

      grep -e "^License ID:" -e "^Virtual Hardware:" -e "^Product Code:" -e "Expiration Date:" -e "^Major Version:" -e "^Minor Version:" \
          -e "^K_LICENSE_ID=" -e "^P_NAME=" -e "^P_CODE=" -e "^P_RLSD=" -e "^P_MAJV=" -e "^P_MINV=" -e "Auto License:" ${OUTVIEW} | sed "s=\r==g" | while read LINE
      do
        ITEM=$(echo ${LINE} | sed 's:[:=]: = :g' | awk '{print $1,$2}')
        case "${ITEM}"
        in
          "License ID")
            LICID=$(echo $(echo ${LINE} | sed "s=^License ID:==g"))
            NBALT_reset
            if test "${TERM}" != "dumb"
            then
              echo "$(tput bold)License id: ${LICID}$(tput sgr0) (VE)"
            fi
            ;;
          "K_LICENSE_ID =")
            LICID=$(echo $(echo ${LINE} | sed "s:^K_LICENSE_ID=::g"))
            NBALT_reset
            if test "${TERM}" != "dumb"
            then
              echo "$(tput bold)License id: ${LICID}$(tput sgr0) (VE)"
            fi
            ;;
          "Virtual Hardware")
            PRDNAM=$(echo $(echo ${LINE} | sed "s=^Virtual Hardware:==g"))
            ;;
          "P_NAME =")
            PRDNAM=$(echo $(echo ${LINE} | sed "s:^P_NAME=::g"))
            ;;
          "Product Code")
            PRDCOD=$(echo $(echo ${LINE} | sed "s=^Product Code:==g"))
            ;;
          "P_CODE =")
            PRDCOD=$(echo $(echo ${LINE} | sed "s:^P_CODE=::g"))
            ;;
          "Expiration Date")
            EXPDAT=$(echo $(echo ${LINE} | sed "s=^Expiration Date:==g"))
            ;;
          "P_RLSD =")
            EXPDAT=$(echo $(echo ${LINE} | sed "s:^P_RLSD=::g"))
            ;;
          "Major Version")
            MAJVER=$(echo $(echo ${LINE} | sed "s=^Major Version:==g"))
            ;;
          "P_MAJV =")
            MAJVER=$(echo $(echo ${LINE} | sed "s:^P_MAJV=::g"))
            ;;
          "Minor Version")
            #--- VE license
            MINVER=$(echo $(echo ${LINE} | sed "s=^Minor Version:==g"))
            compute_cloud_license
            LASTPRD=${PRDNAM}
            ;;
          "P_MINV =")
            #--- VE license
            MINVER=$(echo $(echo ${LINE} | sed "s:^P_MINV=::g"))
            compute_cloud_license
            LASTPRD=${PRDNAM}
            ;;
          "Auto License")
            #--- AutoVE
            if test -n "$(grep 'Auto License:' ${OUTVIEW} | grep -w true)"
            then
              PRDNAM="AutoVE"
              MAJVER=""
              MINVER=""
              compute_cloud_license
              LASTPRD=${PRDNAM}
            fi
            ;;
          # *)
            #echo "      LINE= <${LINE}>"
            # ;;
        esac
      done
    else
      if test "${TERM}" != "dumb"
      then
        echo "${BGORANGE} WARNING [0m Cannot check license expiration from license server."
        tput bold
        echo "license_viewer results:"
        tput sgr0
        echo -n "${FGORANGE}"
        cat ${OUTVIEW}
        tput sgr0
        rm -f ${OUTVIEW} 2>/dev/null
      fi
      rm -f ${NBALTfile} 2>/dev/null
      return 2
    fi
  else
    if test "${TERM}" != "dumb"
    then
      tput bold
      echo "Error running license_viewer."
      tput sgr0
      cat ${OUTVIEW}
    else
      echo "Error running license_viewer."
      cat ${OUTVIEW}
    fi
    rm -f ${OUTVIEW} 2>/dev/null
    return 1
  fi
}

#=============================================================================
# Function: check HASP license content
#=============================================================================
function check_hasp_license
{
  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 "${BGORANGE} WARNING [0m '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 "${BGORANGE} WARNING [0m '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
      return ${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

  OPTHASP=""
  HASPEXE=$(which hasp_srm_view 2>/dev/null)
  if test -z "${HASPEXE}"
  then
    if test "${TERM}" != "dumb"
    then
      if test ! -x /opt/license-server/license_viewer
      then
        echo "Cannot find 'hasp_srm_view' executable file."
        echo "Please verify CHARON is installed and PATH is correctly set."
        echo
        monitorsender "FILENOTFND" "the hasp_srm_view executable file is missing or not executable."
      fi
    fi
    return 3
  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 10
    fi
  done

  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_DEFAULT "Severity Level: ${LVL}" "${MSG}"
      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
      test -n "${FORCEDEXPDAT}" && echo "$(tput bold)Forced expiration date:$(tput sgr0) ${FORCEDEXPDAT}"
      test -n "${FORCEDHOURSLEFT}" && echo "$(tput bold)Forced hours left:$(tput sgr0) ${FORCEDHOURSLEFT}"
      test -n "${FORCEDEXPDAT}" -o -n "${FORCEDHOURSLEFT}" && echo
      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="SEVmajor"
                echo "${NBD} days" >${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} (HASP/Software)<br>" >>${PRODSFILE}
                echo "This Software License may be in cloned state, severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}

                if test "${TERM}" != "dumb"
                then
                  echo "$(tput bold)License id: ${TRYKEYID}$(tput sgr0) (HASP/Software)"
                  echo -n "${FGORANGE}"
                  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="HASP/Software"
          else
            LICHASPTYP="HASP/USB dongle"
          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';')

              if test "${LICHASPTYP}" = "HASP/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 " (${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 "$(tput bold)Description$(tput sgr0): [3${COLDESC:-0}m${LICDESC}[0m"
                  fi
                  echo "<b>Description</b>: ${LICDESC}<br>" >>${PRODSFILE}
                fi
                if test "${RUNHOST}" = "$(hostname -s)" || test "${RUNHOST}" = "$(hostname)"
                then
                  if test "${TERM}" != "dumb"
                  then
                    tput bold
                    echo -n "Served by"
                    tput sgr0
                    echo -n ": ${FGBLUE}this host"
                    tput sgr0
                  fi
                  echo "<b>Served by</b>: ${RUNHOST} (this host)<br>" >>${PRODSFILE}
                else
                  if test "${TERM}" != "dumb"
                  then
                    echo 
                    tput bold
                    echo -n "Served by"
                    tput sgr0
                    echo -n ": ${RUNHOST}"
                  fi
                  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 " (${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 "$(tput bold)Description$(tput sgr0): [3${COLDESC:-0}m${LICDESC}[0m"
                fi
                echo "<b>Description</b>: ${LICDESC}<br>" >>${PRODSFILE}
              fi
              if test "${RUNHOST}" = "$(hostname -s)" || test "${RUNHOST}" = "$(hostname)"
              then
                if test "${TERM}" != "dumb"
                then
                  tput bold
                  echo -n "Served by"
                  tput sgr0
                  echo -n ": ${FGBLUE}this host."
                  tput sgr0
                fi
                echo "<b>Served by</b>: ${RUNHOST} (this host)<br>" >>${PRODSFILE}
              else
                if test "${TERM}" != "dumb"
                then
                  echo
                  tput bold
                  echo -n "Served by"
                  tput sgr0
                  echo -n ": ${RUNHOST}"
                fi
                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=$(date +%d-%b-%Y -d ${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"
                      MSG="License ${LICNUM} approaching termination"
                      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"
                          MSG="License ${LICNUM} approaching termination"
                          #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 "${FGORANGE}";;
                  "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};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}
              if test ${TODDAT} -ge ${XPRDAT}
              then
                echo "$(date +'%Y%m%d;%H%M%S');TODDAT=${TODDAT} (today) ge XPRDAT=${XPRDAT} (expir.)" >>${LOG}
              else
                if test ${TODDAT} -ge ${ALTDAT}
                then
                  echo "$(date +'%Y%m%d;%H%M%S');TODDAT=${TODDAT} (today) ge ALTDAT=${ALTDAT} (alertdate)" >>${LOG}
                else
                  test ${TODDAT} -gt ${MAXDAT} && echo "$(date +'%Y%m%d;%H%M%S');TODDAT=${TODDAT} (today) gt MAXTDAT=${MAXDAT} (no alert sent)" >>${LOG}
                fi
              fi
              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="SEVinfo";;
                    Minor)           COL="SEVminor";;
                    MAJOR)           COL="SEVmajor";;
                    CRITICAL)        COL="SEVcritical";;
                    EXPIRED)         COL="SEVexpired";;
                    *)               COL="SEVdefault";;
                  esac
                  echo "${NBD} days" >${ALERTFLAG}
                  NBALT_incr
                  DREM=$(( ($(date -d ${EXPDAT} +%s) - $(date -d ${TODDAT} +%s)) / 86400 ))
                  if test ${DREM} -ge 0
                  then
                    echo "<b>Product</b>: ${PRDNAM}, Expiration date: ${EXPDAT} (${DREM} days remaining), severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}
                  else
                    DREM=${DREM#-}
                    echo "<b>Product</b>: ${PRDNAM}, Expiration date: ${EXPDAT} (${DREM} days ago), severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}
                  fi
                else
                  if test "${LVL}" = "EXPIRED"
                  then
                    DREM=$(( ($(date -d ${EXPDAT} +%s) - $(date -d ${TODDAT} +%s)) / 86400 ))
                    DREM=${DREM#-}
                    echo "<b>Product</b>: ${PRDNAM}, Expiration date: ${EXPDAT} (${DREM} days ago), severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><br>" >>${PRODSFILE}
                  fi
                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:])
              test -n "${FORCEDHOURSLEFT}" && EXPTIM="${FORCEDHOURSLEFT} hours and 0 minutes"

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

              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 "${FGORANGE}";;
                  "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="SEVinfo";;
                    Minor)           COL="SEVminor";;
                    MAJOR)           COL="SEVmajor";;
                    CRITICAL)        COL="SEVcritical";;
                    EXPIRED)         COL="SEVexpired";;
                    *)               COL="SEVdefault";;
                  esac
                  echo "96 hours" >${ALERTFLAG}
                  NBALT_incr
                  echo "<b>Product</b>: ${PRDNAM}, Time remaining: ${EXPTIM}, severity <span class=${COL}>&nbsp;${LVL}&nbsp;</span><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
}


#-----------------------------------------------------------------------------
# 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 4
fi
MONITORCUS=${CHARONDIR}/utils/$(basename $0).custom

EXPDAT=""
MSG=""
LVL="Informational"
LOG=/opt/charon/log/charon_expchk.log
NOLICENSEFLAG=${ETCCHARON}/CharonToolkit.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
    echo "[31mERROR[0m: must be root !"
    echo -n "[44m[37mPress enter[0m"
    read ENTER
    tput cuu1;tput el
  else
    echo "Must be root !"
  fi
  echo
  exit 1
fi

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

NOMAIL=0
FORCEDEXPDAT=""
FORCEDHOURSLEFT=""
NBD=7

echo "$(date +'%Y%m%d;%H%M%S');BEGIN" >>${LOG}
echo "$(date +'%Y%m%d;%H%M%S');P1=<$1>, P2=<$2>, P3=<$3>, P4=<$4>" >>${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'=')
      FORCEDEXPDAT=$(date +%d-%b-%Y -d ${FORCEDEXPDAT})
      ;;
    -hoursleft=*)
      if test -n "$(echo $1 | cut -f2 -d'=' | egrep '^[0-9]{1,8}$')"
      then
        FORCEDHOURSLEFT=$(echo $1 | cut -f2 -d'=')
      else
        echo "${BGORANGE} WARNING [0m Invalid parameter '$1'. Skipping."
      fi
      ;;
    -h|--help)
      Usage
      ;;
    *)
      if test -z "$(echo $1 | tr -d [:digit:])"
      then
        NBD=$1
      else
        if test "${TERM}" != "dumb"
        then
          echo "${BGORANGE} WARNING [0m Invalid parameter '$1'. Skipping."
        else
          echo "WARNING: Invalid parameter '$1'. Skipping."
        fi
      fi
      ;;
  esac
  shift        
done

#--- Identify what kind of license is used and analyze its content
CHKLIC=0
if test -x /usr/sbin/aksusbd
then
  check_hasp_license
  CHKLIC=1
fi
if test -x /opt/license-server/license_viewer
then
  check_cloud_license
  CHKLIC=1
fi
if test ${CHKLIC} -eq 0
then
  test "${TERM}" != "dumb" && tput bold
  echo "ERROR: Cannot determine the license type used!"
  test "${TERM}" != "dumb" && tput sgr0
  echo "Please check HASP driver or license server is installed."
fi

if test -e ${ALERTFLAG}
then
  if test -s ${ALERTFLAG}
  then
    ALTREQMSG=$(cat ${ALERTFLAG})
  else
    ALTREQMSG="${NBD} days"
  fi
  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}
      PRIO="LOW"
      test -n "$(grep '\&nbsp;Minor\&nbsp;'    ${PRODSFILE})" && PRIO="DEFAULT"
      test -n "$(grep '\&nbsp;MAJOR\&nbsp;'    ${PRODSFILE})" && PRIO="HIGH"
      test -n "$(grep '\&nbsp;CRITICAL\&nbsp;' ${PRODSFILE})" && PRIO="HIGH"
      test -n "$(grep '\&nbsp;EXPIRED\&nbsp;'  ${PRODSFILE})" && PRIO="HIGH"
      ${CHARONDIR}/utils/charon_check.alertcmd "EXPCHK_${PRIO}" "Alert requested ${ALTREQMSG} 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