#!/bin/bash
#-------------------------------------------------------------------------------
# charon_menu_showlic
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2023 STROMASYS.
# All rights reserved.
# Products: AXP/VAX + PAR
#set -x
VERSION=2.1

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

#=============================================================================
# Function: check cloud license content
#=============================================================================
function compute_cloud_license
{
  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" -d "${EXPDAT}")
    case "${EXPDAT}"
    in 
      "Unlimited")
        LINE="${LINE} (unlimited)"
        ;;
      *)
        XPRDAT=$(date +%Y%m%d -d "${EXPDAT}")
        ALTDAT=$(date +%Y%m%d -d "$(echo ${EXPDAT} | awk '{print $1}') -${NBD} days")
        let DIFF=($(date +%s -d ${EXPDAT})-$(date +%s -d ${TODDAT}))/86400
        if test ${TODDAT} -ge ${XPRDAT}
        then
          LINE="${LINE} (expired)"
        else
          if test ${TODDAT} -ge ${ALTDAT}
          then
            LINE="${LINE} (soon expired, $DIFF days remaining)"
          else
            LINE="${LINE} ($DIFF days remaining)"
          fi
        fi
        ;;
    esac
  else
    #--- Hour limited license
    #    Example: Expiration Date: 240 hour(s)
    EXPTIM=$(echo ${EXPDAT} | awk '{print $1}')
    EXPHOUR=$(echo ${EXPTIM} | awk '{print $1}')
    if test ${EXPHOUR} -eq 0
    then
      LINE="${LINE} (expired)"
    else
      LINE="${LINE} (soon expired, less than 72 hours remaining)"
    fi
  fi
}

#-------------------------------------------------------------------------------
# Main script
#-------------------------------------------------------------------------------
MAILTOFILE="/tmp/charon_menu_showlic.mailto"
DONGLESFILE="${CHARONDIR}/utils/charon_licenses.list"
EXCODE=0

get_preferences
TODDAT=$(date +%Y%m%d)

display_header "License details (HASP and VE)"

if test -x /usr/sbin/aksusbd
then
  #--- HASP license
  display_licfound

  OPTHASP=""
  HASPEXE=$(which hasp_srm_view 2>/dev/null)
  if test -z "${HASPEXE}"
  then
    if test ! -x /opt/license-server/license_viewer
    then
      #--- If no VE license server, display error and exit
      echo "Cannot find 'hasp_srm_view' executable file."
      echo "Please verify CHARON is installed and PATH is correctly set."
      Press_Enter
      exit 1
    fi
  else
    test -n "$(strings ${HASPEXE} | grep ^-all)" && OPTHASP="-all"

    #--- 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 read the installation guide and 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

    if test ${ATDX} -eq 1
    then
      Press_Enter
      exit 2
    fi

    OUTVIEW="/tmp/$(basename $0)_$(date +%Y%m%d_%H%M%S).view"
    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 N=0
    while test 1
    do
      N=N+1
      sleep 2
      echo -n "."
      test -z "$(at -l | grep -w ^${ATNUM})" && break
      if test $N -gt 30
      then
        >${OUTVIEW}
        break
      fi
    done

    echo
    tput cuu1;tput el

    LICNUM=$(grep "^The License Number" ${OUTVIEW} | sed "s=\(^.*Number: \)\(.*\)=\2=g" | tr "\r\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

    if test -s ${OUTP}
    then
      if test -n "$(grep 'License type:' ${OUTP})"
      then
        tput bold
        echo "Licenses found (local and remote):"
        tput sgr0
        echo
        echo "License number Type Key ID"
        if test "${SEMIGRAPH}" = "enabled"
        then
          tput smacs
          echo "qqqqqqqqqqqqqq qqqq qqqqqqqqqqqqqqqqqqqq"
          tput rmacs
        else
          echo "-------------- ---- --------------------"
        fi
        if test -s ${DONGLESFILE}
        then
          tput cuu1
          tput cuu1
          tput hpa 41
          tput bold
          echo "Description"
          tput sgr0
          tput hpa 41
          if test "${SEMIGRAPH}" = "enabled"
          then
            tput smacs
            echo "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"
            tput rmacs
          else
            echo "--------------------------------------"
          fi
        fi

        grep -e "^Trying to connect to the key" -e "^The License" -e "^License type:" -e "^Sentinel HASP key not found or of improper type" -e "^-------" ${OUTP} | while read LINE
        do
          case "$(echo ${LINE} | awk '{print $1,$2}')"
          in
            "Trying to")
              KEYID=$(echo ${LINE} | cut -f2 -d':' | tr -dc [:digit:])
              LICNUM="(empty)"
              ;;
            "The License")
              if test "$(echo ${LINE} | awk '{print $3}')" = "Number:"
              then
                LICNUM=$(echo ${LINE} | sed "s=\(^.*Number: \)\(.*\)=\2=g" | tr -d "\r\n")
                LICDESC=$(grep "^${LICNUM};" ${DONGLESFILE} 2>/dev/null | cut -f2 -d';')
                COLDESC=$(grep "^${LICNUM};" ${DONGLESFILE} 2>/dev/null | cut -f3 -d';')
              fi
              ;;
            "License type:")
              if test "$(echo ${LINE} | awk '{print $3}')" = "Software"
              then
                LICHASPTYP="Soft"
              else
                LICHASPTYP="USB "
              fi
              ;;
            "Sentinel HASP")
              LICNUM="(ERROR)"
              ;;
            *)
              if test "$(echo ${LINE} | cut -c1-5)" = "-----"
              then
                if test "${TERM}" != "dumb"
                then
                  printf "%-14s %-4s %-20s " ${LICNUM} ${LICHASPTYP} ${KEYID}
                  if test -n "${LICDESC}"
                  then
                    echo "[3${COLDESC:-0}m${LICDESC}[0m"
                  else
                    echo
                  fi
                fi
              fi
              ;;
          esac
        done
        echo

        sed -e "s=\(^License Manager running at host: $(hostname)$\)=\1 (this host)=g" \
            -e "s=\(^License Manager running at host: $(hostname -s)$\)=\1 (this host)=g" \
            ${OUTP} >${OUTP}.tmp
        rm -f ${OUTP} 2>/dev/null
        KEYID=""
        cat ${OUTP}.tmp | 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
                KEYID=$(echo ${LINE} | cut -f2 -d':' | tr -dc [:digit:])
                LICNUM=""
                NOTFOUND=0
              fi
              echo "${LINE}" >>${OUTP}
              ;;
            "The License")
              if test "$(echo ${LINE} | awk '{print $3}')" = "Number:"
              then
                LICNUM=$(echo ${LINE} | sed "s=\(^.*Number: \)\(.*\)=\2=g" | tr -d "\r\n")
              fi
              echo "${LINE}" >>${OUTP}
              ;;
            "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 '(')
                  EXPDAT=$(echo ${EXPDAT} | sed "s= and = =g" | tr -d [:cntrl:])
                  case "${EXPDAT}"
                  in 
                    "01-Jan-1970")
                      echo "${LINE} (unlimited)" >>${OUTP}
                      ;;
                    "Unlimited")
                      echo "${LINE} (unlimited)" >>${OUTP}
                      ;;
                    "SL license not started yet")
                      echo "${LINE} (Software license not started yet)" >>${OUTP}
                      ;;
                    *)
                      XPRDAT=$(date +%Y%m%d -d "${EXPDAT}")
                      ALTDAT=$(date +%Y%m%d -d "${EXPDAT} -14 days")
                      let DIFF=($(date +%s -d ${EXPDAT})-$(date +%s -d ${TODDAT}))/86400
                      if test ${TODDAT} -ge ${XPRDAT}
                      then
                        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)
                            echo "${LINE} (soon expired, $DIFF days remaining)" >>${OUTP}
                          else
                            #--- Special case for CHARON-SSP: the license expires at 02:00 AM
                            if test $(date +%H) -ge 2
                            then
                              echo "${LINE} (expired)" >>${OUTP}
                            else
                              echo "${LINE} (soon expired, $DIFF days remaining)" >>${OUTP}
                            fi
                          fi
                        else
                          echo "${LINE} (expired)" >>${OUTP}
                        fi
                      else
                        if test ${TODDAT} -ge ${ALTDAT}
                        then
                          echo "${LINE} (soon expired, $DIFF days remaining)" >>${OUTP}
                        else
                          echo "${LINE} ($DIFF days remaining)" >>${OUTP}
                        fi
                      fi
                      ;;
                  esac
                  ;;
                "time"|"remaining:")
                  #--- 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:])
                  EXPHOUR=$(echo ${EXPTIM} | awk '{print $1}')
                  EXPMINS=$(echo ${EXPTIM} | awk '{print $4}')
                  if test ${EXPHOUR} -eq 0 -a ${EXPMINS} -eq 0
                  then
                    echo "${LINE} (expired)" >>${OUTP}
                  else
                    if test ${EXPHOUR} -lt 72
                    then
                      echo "${LINE} (soon expired, less than 72 hours remaining)" >>${OUTP}
                    else
                      echo "${LINE}" >>${OUTP}
                    fi
                  fi
                  ;;
              esac
              ;;
            *)
              if test "$(echo ${LINE} | cut -c1-5)" = "-----"
              then
                if test -z "${LICNUM}"
                then
                  if test ${NOTFOUND:-0} -eq 0
                  then
                    echo "No License information detected (section is empty)." >>${OUTP}
                  fi
                fi
                echo "${LINE}" >>${OUTP}
              elif test -n "$(echo ${LINE} | grep 'not found or of improper type')"
              then
                NOTFOUND=1
                echo "${LINE}" >>${OUTP}
                if test -n "${KEYID}"
                then
                  if test $(ls -1 /var/hasplm/installed/68704/${KEYID}*.v2c 2>/dev/null | wc -l) -gt 0
                  then
                    echo >>${OUTP}
                    echo "This Software License may be in cloned state." >>${OUTP}
                    echo "Open the 'Sentinel Admin Control Center' to confirm." >>${OUTP}
                    echo "If this is confirmed, please remove it using the 'License update tool' menu" >>${OUTP}
                    echo "option and if necessary, generate a new one using the 'Request for new" >>${OUTP}
                    echo "license or license update' menu option." >>${OUTP}
                  fi
                fi
              else
                echo "${LINE}" >>${OUTP}
              fi
              ;;
          esac
        done

        ask_editor
        if test -n "${EDI}"
        then
          if test -z "$(echo ${EDI}|grep vim)"
          then
            ${EDI} ${OUTP} 2>/dev/null
          else
            ${EDI} -u ${CHARONDIR}/utils/charonlic.vimrc ${OUTP} 2>/dev/null
          fi
        fi
        echo
      else
        echo
        tput bold
        cat ${OUTP}
        tput sgr0
        echo
        Press_Enter
        echo "[44m[37m USB dongle driver status (aksusbd) [0m"
        systemctl -l --lines=6 --no-pager status aksusbd
        Press_Enter
      fi
    else
      tput bold
      echo "Output file empty, please check your dongle is connected and retry."
      tput sgr0
      Press_Enter
    fi
  fi
fi

if test -x /opt/license-server/license_viewer
then
  #--- VE license
  OUTVIEW="/tmp/license_viewer.$$.txt"
  OUTP="/tmp/license_viewer.$$.out"
  rm -f ${OUTVIEW} ${OUTP} 2>/dev/null

  typeset -i N=0
  typeset -i I=0

  /opt/license-server/license_viewer >${OUTVIEW} 2>&1
  if test $? -eq 0
  then
    if test -z "$(grep 'Failed to retrieve the license' ${OUTVIEW})"
    then
      PRDNAM=""
      LASTLIC=""

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

      cat ${OUTVIEW} | sed "s=\r==g" | while read LINE
      do
        ITEM=$(echo ${LINE} | sed 's:[:=]: = :g' | awk '{print $1,$2}')
        case "${ITEM}"
        in
          "Expiration Date")
            EXPDAT=$(echo $(echo ${LINE} | sed "s=^Expiration Date:==g"))
            compute_cloud_license
            ;;
          "P_RLSD =")
            EXPDAT=$(echo $(echo ${LINE} | sed "s:^P_RLSD=::g"))
            compute_cloud_license
            ;;
          *)
            #echo "      LINE= <${LINE}>"
            ;;
        esac
        echo "${LINE}" >>${OUTP}
      done
      ask_editor
      if test -n "${EDI}"
      then
        if test -z "$(echo ${EDI}|grep vim)"
        then
          ${EDI} ${OUTP} 2>/dev/null
        else
          ${EDI} -u ${CHARONDIR}/utils/charonlic.vimrc ${OUTP} 2>/dev/null
        fi
      fi
    else
      tput bold
      echo "license_viewer results:"
      tput sgr0
      echo -n "${FGORANGE}"
      cat ${OUTVIEW}
      tput sgr0
      EXCODE=1
    fi
  else
    tput bold
    echo "Error running license_viewer:"
    tput sgr0
    echo -n "${FGORANGE}"
    cat ${OUTVIEW}
    tput sgr0
    EXCODE=2
  fi
  rm -f ${OUTVIEW} ${OUTP} 2>/dev/null
else
  echo
  tput bold
  echo "ERROR: Cannot determine the license type used!"
  tput sgr0
  echo "Please check HASP driver or license server is installed."
  echo
  EXCODE=3
fi

exit ${EXCODE:-0}
