#!/bin/bash
#-------------------------------------------------------------------------------
# charon_menu_c2v
#-------------------------------------------------------------------------------
# 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

MAILTOFILE="/tmp/charon_menu_c2v.mailto"

get_preferences

function check_and_send_mail
{
  if test -n "${C2VLIST}"
  then
    echo
    if test $(echo ${LICENSEKEYIDS} | wc -w) -gt 1
    then
      echo "C2V files generated: ${FGBLUE}${C2VLIST}"
    else
      echo "C2V file generated: ${FGBLUE}${C2VLIST}"
    fi
    tput sgr0
    echo
    while test 1
    do
      printf "Do you want to send file via mail (y/n) ? "
      read CH
      case "${CH}"
      in
        y|Y)
          select_mailto
          if test -s ${MAILRECIPFILE}
          then
            MAILTO=$(cat ${MAILRECIPFILE})
            echo
            echo "Sending mail to ${MAILTO}..."
            TMPMAIL=/tmp/charon_menu_c2v.$$

            MAILFROM=$(cat ${MAILFRFILE} 2>/dev/null)
            if test -z "${MAILFROM}"
            then
              echo "From: $(whoami)@$(hostname)" >${TMPMAIL}
            else
              if test -n "$(echo ${MAILFROM} | grep '@')"
              then
                echo "From: ${MAILFROM}" >${TMPMAIL}
              else
                echo "From: ${MAILFROM}<$(whoami)@$(hostname)>" >${TMPMAIL}
              fi
            fi

            echo "To: ${MAILTO}" >>${TMPMAIL}

            if test "$1" = "c2v"
            then
              echo "Subject: [${MAILTAG:-CHARON}] C2V file / HASP License" >>${TMPMAIL}
            else
              echo "Subject: [${MAILTAG:-CHARON}] C2V file / Collect for Software License" >>${TMPMAIL}
            fi

            BOUNDARY="$$CHARONSENDMAIL$(basename $0)$$"
            echo "Mime-Version: 1.0;" >>${TMPMAIL}
 
            C2VFIL="$(hostname -s)_$(date +%Y%m%d-%H%M%S)_c2v.zip"

            echo "Content-Type: multipart/mixed; boundary=${BOUNDARY}" >>${TMPMAIL}
            echo "" >>${TMPMAIL}
            echo "Please find attached C2V files: ${C2VFIL}" >>${TMPMAIL}
            echo "" >>${TMPMAIL}
            echo "License keyid(s): ${LICENSEKEYIDS}" >>${TMPMAIL}
            echo "" >>${TMPMAIL}
            echo "--${BOUNDARY}" >>${TMPMAIL}
            echo "Content-Type: text/plain; charset=\"ISO-8859-1\";" >>${TMPMAIL}
            echo "Content-Disposition: inline;" >>${TMPMAIL}
            echo "" >>${TMPMAIL}
            echo "Please find attached C2V file: ${C2VFIL}" >>${TMPMAIL}
            echo "" >>${TMPMAIL}
            echo "License keyid(s): ${LICENSEKEYIDS}" >>${TMPMAIL}
            echo "" >>${TMPMAIL}
            echo "--${BOUNDARY}" >>${TMPMAIL}
            echo "Content-Type: application/octet-stream; name=$(basename ${C2VFIL});" >>${TMPMAIL}
            echo "Content-Transfer-Encoding: base64;" >>${TMPMAIL}
            echo "Content-Disposition: Attachment; filename=${C2VFIL}" >>${TMPMAIL}
            echo "" >>${TMPMAIL}

            test -e ${C2VFIL} && rm -f ${C2VFIL}
            zip -j ${C2VFIL} ${C2VLIST}

            base64 ${C2VFIL} >>${TMPMAIL}
            echo "" >>${TMPMAIL}
            echo "--${BOUNDARY}--" >>${TMPMAIL}

            sendmail -t -i <${TMPMAIL}
            if test $? = 0
            then
              echo "Done."
              rm -f ${TMPMAIL} ${C2VFIL}
            else
              echo "${FGORANGE}Failed![0m"
            fi
          fi
          break
          ;;
        n|N)
          break
          ;;
        *)
          tput cuu1;tput ed
          ;;
      esac
    done
  else
    tput bold
    echo "Failed to generate C2V file. Please contact support."
    tput sgr0
    echo
    Press_Enter
  fi
}

if test ! -w /tmp
then
  display_header "Request for new license or license update (send C2V file)"
  echo
  echo "No privileges to write in /tmp folder. Please connect as 'root' and retry"
  echo
  Press_Enter
  exit 1
fi

if test ! -x /usr/sbin/aksusbd
then
  display_header "Request for new license or license update (send C2V file)"
  echo
  echo "${FGORANGE}WARNING[0m: aksusbd is not installed (HASP license) !"
  echo
  Press_Enter
  exit 1
fi

OPTHASP=""
HASPEXE=$(which hasp_srm_view 2>/dev/null)
if test -z "${HASPEXE}"
then
  echo "Cannot find 'hasp_srm_view' executable file."
  echo "Please verify CHARON is installed and PATH is correctly set."
  Press_Enter
  exit 1
else
  test -n "$(strings ${HASPEXE} | grep ^-all)" && OPTHASP="-all"
fi

while test 1
do
  display_header "Request for new license or license update (send C2V file)"

  systemctl -q is-active aksusbd
  if test $? -ne 0
  then
    tput bold
    echo "'aksusbd' service is not running. Cannot continue."
    tput sgr0
    echo
    echo "Please use option 'License driver management (aksusbd)' from the menu to start"
    echo "the service"
    echo
    Press_Enter
    exit 3
  fi

  display_licfound
  NBDONGLES=$(/usr/bin/lsusb -d 0529:0001 | wc -l)
  NBSL=$(ls /var/hasplm/installed/68704/*_base.v2c 2>/dev/null | wc -l)
 
  echo "[1mCollect information to[0m:"
  echo "1 - Update a license (dongle or software license)"
  echo "2 - Generate a Software License (fingerprint)"
  echo

  echo -n "Enter your choice (q to quit) : "
  read ANS
  case "${ANS}"
  in
    1)
      if test ${NBDONGLES} -eq 0 -a ${NBSL} -eq 0
      then
        echo
        tput bold
        echo "This option requires at least a USB license dongle connected or a software"
        echo "license already installed."
        tput sgr0
        echo
        Press_Enter
      else
        echo
        OUTVIEW="/tmp/$(basename $0)_$(date +%Y%m%d_%H%M%S).view"
        echo -n "Please wait, getting license(s) keyid(s)..."
        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

        test -e ${OUTVIEW}.lnk.tmp && rm -f ${OUTVIEW}.lnk.tmp 2>/dev/null
        TL="DG"
        RUNHOST=""
        grep -e "^Trying to connect to the key" -e "^The License Number" -e "^The Sentinel SL KeyId" -e "^License Manager running at host" -e "^-----" ${OUTVIEW} | while read LNK
        do
          LNK1=$(echo ${LNK} | cut -f1 -d':')
          LNK2=$(echo ${LNK} | cut -f2 -d':' | tr -d [:blank:] | tr -d [:cntrl:])
          case "${LNK1}"
          in
            "Trying to connect to the key")
              KEYID=${LNK2}
              LNUMB=""
              ;;
            "License Manager running at host")
              RUNHOST=${LNK2}
              ;;
            "The Sentinel SL KeyId")
              TL="SL"
              ;;
            "The License Number")
              LNUMB=${LNK2}
              ;;
            *)
              if test "$(echo ${LNK} | cut -c1-5)" = "-----"
              then
                if test "${RUNHOST}" = "$(hostname -s)" || test "${RUNHOST}" = "$(hostname)"
                then
                  echo "Number:${LNUMB:-Empty};KeyId:${KEYID}" >>${OUTVIEW}.lnk.tmp
                  if test -z "${LNUMB}"
                  then
                    echo "+ Found empty license (key id ${KEYID})."
                  else
                    echo "+ Found license ${LNUMB} (key id ${KEYID})."
                  fi
                else
                  echo "- License number ${LNUMB} skipped, served by another host (${RUNHOST})."
                fi
              fi
              ;;
          esac
        done
        LICENSEIDNUM=$(cat ${OUTVIEW}.lnk.tmp)
        LICENSEKEYIDS=$(cat ${OUTVIEW}.lnk.tmp | sed "s=^.*KeyId:\(.*\)$=\1=g")

        if test -n "${LICENSEKEYIDS}"
        then
          echo
          C2VLIST=""
          for L in ${LICENSEIDNUM}
          do
            LICENSENUM=$(echo ${L} | cut -f1 -d';' | cut -f2 -d':')
            LICENSEKID=$(echo ${L} | cut -f2 -d';' | cut -f2 -d':')

            if test "${LICENSENUM}" = "Empty"
            then
              OUTC2V="/tmp/Empty${LICENSEKID}_$(date +%Y%m%d_%H%M%S).c2v"
              echo -n "Please wait, generating C2V file for empty license (keyid ${LICENSEKID})..."
            else
              OUTC2V="/tmp/${LICENSENUM}_$(date +%Y%m%d_%H%M%S).c2v"
              echo -n "Please wait, generating C2V file for license ${LICENSENUM}..."
            fi
            touch ${OUTC2V}

            OPTKEY=""
            test -n "$(strings ${HASPEXE} | grep 'collect C2V file for specific local key')" && OPTKEY="-key ${LICENSEKID}"
  
            hasp_srm_view -c2v ${OUTC2V} ${OPTKEY} >${OUTC2V}.out

            if test -z "$(grep 'License type:' ${OUTC2V}.out)"
            then
              echo hasp_srm_view -c2v ${OUTC2V} ${OPTKEY} | at now 2>/dev/null
              typeset -i N=0
              while test 1
              do
                N=N+1
                sleep 1
                echo -n "."
                CHK=$(tail -1 ${OUTC2V}|grep "^</hasp_info>$")
                test -n "${CHK}" && break
                if test $N -gt 20
                then
                  rm -f ${OUTC2V}
                  break
                fi
              done
              if test -s ${OUTC2V}
              then
                C2VLIST="${C2VLIST} ${OUTC2V}"
              else
                echo
                echo "[31mCannot generate C2V file for license keyid ${LICENSEKID}[0m"
              fi
            else
              C2VLIST="${C2VLIST} ${OUTC2V}"
            fi
            test "$1" != "-debug" && rm -f ${OUTC2V}.out 2>/dev/null
            echo
          done
          check_and_send_mail c2v
        else
          tput bold
          echo "Cannot get the license number. Verify the license dongle is connected."
          tput sgr0
          echo
          Press_Enter
        fi  
        test "$1" != "-debug" && rm -f ${OUTVIEW} ${OUTVIEW}.lnk.tmp 2>/dev/null
        break
      fi
      ;;
    2)
      OUTC2V="/tmp/$(hostname -s)_$(date +%Y%m%d_%H%M%S).c2v"
      C2VLIST=${OUTC2V}
      hasp_srm_view -fgp ${OUTC2V}
      LICENSENUM=$(hostname -s)
      check_and_send_mail fgp
      break
      ;;
    q)
      break
      ;;
    *)
      tput cuu1;tput el
      ;;
  esac
done

exit
