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

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

#=============================================================================
# Function: check cloud license content
#=============================================================================
function compute_cloud_license
{
  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}")

    LVL="Informational"
    case "${EXPDAT}"
    in 
      "Unlimited")
        XPRDAT="999999999999"
        ALTDAT="999999999999"
        MAXDAT="999999999999"
        ;;
      *)
        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")
        LVL="NEUTRAL"
        if test ${TODDAT} -ge ${XPRDAT}
        then
          LVL="EXPIRED"
        else
          if test ${TODDAT} -ge ${ALTDAT}
          then
            LVL="Informational"
            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}            
              fi
            done
          fi
        fi
        ;;
    esac
    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"
  else
    #--- Hour limited license
    #    Example: Expiration Date: 240 hour(s)
    EXPTIM=$(echo ${EXPDAT} | awk '{print $1}')

    LVL="Informational"
    EXPHOUR=$(echo ${EXPTIM} | awk '{print $1}')
    if test ${EXPHOUR} -eq 0
    then
      LVL="EXPIRED"
    else
      test ${EXPHOUR} -lt 72 && LVL="Minor"
      test ${EXPHOUR} -lt 48 && LVL="MAJOR"
      test ${EXPHOUR} -lt 24 && LVL="CRITICAL"
    fi

    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
}

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
        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
      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"))
            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"))
            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
      echo "${FGORANGE}WARNING[0m: Cannot read license content."
      echo
      tput bold
      echo "license_viewer results:"
      tput sgr0
      cat ${OUTVIEW}
      rm -f ${OUTVIEW} 2>/dev/null
      exit 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
    exit 1
  fi
}


#-------------------------------------------------------------------------------
# Main script
#-------------------------------------------------------------------------------
EXCODE=0

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

if test -x /opt/license-server/license_viewer
then
  while test 1
  do
    display_header "License removal"
    check_cloud_license
    echo
    echo -n "${FGORANGE}Please confirm you want to remove this license (y/n):[0m "
    read ANS
    case "${ANS}"
    in
      y|Y)
        #HERE: record the operation in a log file ?
        echo 'yes' | /opt/license-server/c2v -t /tmp/$(hostname -s)_$(date +%Y%m%d_%H%M%S).tfr >/dev/null
        if test $? -ne 0
        then
          echo "${FGORANGE}Failed.[0m"
          Press_Enter
        fi
        ;;
      n|N)
        break
        ;;
      *)
        tput cuu1;tput ed
        ;;
    esac
  done
else
  display_header "License removal"
  echo
  echo "${FGORANGE}WARNING[0m: License server package is not installed (VE license) !"
  echo "         Please ensure you are running this utility on the license server."
  EXCODE=3
fi

exit ${EXCODE:-0}
