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

DONGLESFILE="${CHARONDIR}/utils/charon_licenses.list"

get_preferences

test -d /var/hasplm.bck || mkdir -p /var/hasplm.bck

#--- To solve a problem with previous version
if test -d /var/hasplm/installed/68704.bck
then
  mv -f /var/hasplm/installed/68704.bck/* /var/hasplm.bck/ 2>/dev/null
  rm -rf /var/hasplm/installed/68704.bck
fi

#-------------------------------------------------------------------------------
# Display header
#-------------------------------------------------------------------------------
function disp_header
{
  display_header "License update tool (apply V2C file)"
  echo
}

#-------------------------------------------------------------------------------
# Graphical User Interface
#-------------------------------------------------------------------------------
function use_gui
{
  echo >>${CHARONDIR}/log/$(basename $0).log
  echo $(date +"%d-%b-%Y %H:%M:%S") "------------------------------" >>${CHARONDIR}/log/$(basename $0).log

  FIRLOG=${CHARONDIR}/log/$(basename $0).log
  /usr/bin/firefox http://localhost:1947/_int_/checkin.html 2>${FIRLOG}
  if test $? != 0
  then
    if test -n "$(grep 'Running Firefox as root' ${FIRLOG} | grep 'not supported')"
    then
      #--- extracting the user in the error output file ("who am i" could also work)
      FIRUSR=$(sed "s=\(^.* owned by \)\(.*\)\(\..$\)=\2=g" ${FIRLOG})
      su ${FIRUSR} -c "/usr/bin/firefox http://localhost:1947/_int_/checkin.html"
    fi
  else
    echo "Firefox failed to execute:"
    cat ${FIRLOG}
    echo
    Press_Enter
  fi
}

#-------------------------------------------------------------------------------
# Selection and application of V2C files
#-------------------------------------------------------------------------------
function apply_v2c_file
{
  LICFOLDER=$(cat ${CHARONLICFOLDER} 2>/dev/null)
  echo
  if test -d ${LICFOLDER}
  then
    while test 1
    do
      DDAT=$(date +"%x")
      echo "[44m[37m Available license files [0m"
      TMPFIL="/tmp/$(basename $0).files.tmp"
      rm -f ${TMPFIL} 2>/dev/null
      typeset -i N=0
      LASTLI=""
      LINECOL=${FGBLUE}
      for LINE in $(ls -1 ${LICFOLDER}/*.v2c 2>/dev/null | grep -v _fmt\.v2c | sort -t "_" -k2 -nk1)
      do
        BASLINE=$(basename ${LINE} | cut -f2 -d"_")
        if test "${BASLINE}" != "${LASTLI}"
        then
          test "${LINECOL}" = "" && LINECOL=${FGBLUE} || LINECOL=""
        fi
        LASTLI=${BASLINE}
        FMTLI=$(echo ${LINE} | sed "s=\.v2c$=_fmt.v2c=")
        if test -s ${FMTLI}
        then
          N=N+1
          FDAT=$(date -r ${FMTLI} +"%x")
          test "${FDAT}" = "${DDAT}" && LINECOL="[32m"
          printf "${LINECOL}%2d - %s" ${N} $(basename ${FMTLI})
          echo "[0m"
          echo ${FMTLI} >>${TMPFIL}
        fi
        N=N+1
        FDAT=$(date -r ${LINE} +"%x")
        test "${FDAT}" = "${DDAT}" && LINECOL="[32m"
        DISPDAT=$(date -r ${LINE} +"%d-%b-%Y %H:%M:%S")
        printf "${LINECOL}%2d - %s (%s)" ${N} $(basename ${LINE}) "${DISPDAT}"
        echo "[0m"
        echo ${LINE} >>${TMPFIL}
      done
      echo
      if test $N -gt 0
      then
        echo "[1m[31mNote[0m: If an '_fmt.v2c' file is provided (dongles only), please install it first."
        echo
        echo "Multiple selections available, comma or blank separated (example: 1,2 3)"
        echo -n "Enter your choice (q to quit) : "
        read ANS
        test "${ANS}" = "q" -o -z "${ANS}" && break
        echo
        echo "[1mError codes explanations:[0m:"
        cat <<EOF
- Code 18 means the dongle is not connected
- Code 55 means you tried to apply a V2C file with an update counter that
  is out of sequence with update counter in the Sentinel protection key
- Code 65 means the (software) license has already been applied
EOF
        echo
        ALRSEL="X"
        for SEL in $(echo ${ANS} | tr "," " ")
        do
          if test -z "$(echo ${SEL} | tr -d [:digit:])"
          then
            PAR="u"
            if test -x ${CHARONDIR}/bin/${UPDATE_EXE}
            then
              if test -z "$(echo ${ALRSEL} | grep -w ${SEL})"
              then
                LICFILE=$(cat -n ${TMPFIL} | grep -w ${SEL} | awk '{print $2}')
                if test -n "${LICFILE}"
                then
                  ALRSEL="${ALRSEL} ${SEL}"
                  typeset -ix MISSTAG=0
                  for TAG in '<?xml' '<hasp_info>' '<haspscope>' '<vendor id="68704">' \
                             '<hasp id=' '</vendor>' '</haspscope>' '<v2c>' '</v2c>'   \
                             '</hasp_info>'
                  do
                    grep -q "${TAG}" ${LICFILE}
                    if test $? != 0
                    then
                      echo "${BGORANGE} WARNING [0m Missing tag ${TAG} in $(basename ${LICFILE})! Please check file content."
                      MISSTAG=1
                    fi
                  done
                  if test ${MISSTAG} -eq 0
                  then
                    echo "${FGBLUEBOLD}Applying $(basename ${LICFILE}) ...[0m"
                    ${CHARONDIR}/bin/${UPDATE_EXE} ${PAR} ${LICFILE}
                    sleep 1
                  else
                    echo "[30m[41m ERROR [0m Cannot apply license file $(basename ${LICFILE})"
                  fi
                else
                  echo
                  echo "${BGORANGE} WARNING [0m Invalid selection number '${SEL}'"
                fi
              else
                echo
                echo "${BGORANGE} WARNING [0m Duplicate selection '${SEL}'"
              fi
            else
              echo "Cannot execute ${CHARONDIR}/bin/${UPDATE_EXE} file!"
              echo >>${CHARONDIR}/log/$(basename $0).log
              echo $(date +"%d-%b-%Y %H:%M:%S") " Cannot execute ${CHARONDIR}/bin/${UPDATE_EXE} file" >>${CHARONDIR}/log/$(basename $0).log
            fi
          else
            echo "Bad selection: '${SEL}' skipped (must be numeric)"
          fi
        done
      else
        echo "${FGORANGE}No .v2c file found in the folder...[0m"
      fi
      Press_Enter
      break
    done
  else
    echo "The currently defined license folder does not exist. Please reset"
    Press_Enter
  fi    
}

#-------------------------------------------------------------------------------
# Remove software license
#-------------------------------------------------------------------------------
function remove_sl
{
  echo
  NSL_BEF=$(ls /var/hasplm/installed/68704/*.v2c 2>/dev/null | cut -f1 -d "_" | sort -u | wc -l)
  for LIC in $(ls /var/hasplm/installed/68704/*_base.v2c 2>/dev/null)
  do
    LICID=$(basename ${LIC} | cut -f1 -d "_")
    tput bold
    echo "License Id: ${LICID} ($(date '+%d-%b-%Y %H:%M' -r ${LIC}))"
    tput sgr0
    for UPD in $(ls /var/hasplm/installed/68704/${LICID}_update*.v2c 2>/dev/null)
    do
      UPDV=$(basename ${UPD} | cut -f2 -d "_" | cut -f1 -d ".")
      echo "- ${UPDV} ($(date '+%d-%b-%Y %H:%M' -r ${UPD}))"
    done
    while test 1
    do
      echo -n "${FGBLUE}Do you want to remove it (y/n) ?[0m "
      read ANS
      case "${ANS}"
      in
        y|Y)
          mv ${LIC} /var/hasplm.bck/$(basename ${LIC}).archived
          for UPD in $(ls /var/hasplm/installed/68704/${LICID}_update*.v2c 2>/dev/null)
          do
            mv ${UPD} /var/hasplm.bck/$(basename ${UPD}).archived
          done
          echo "Files have been archived."
          break
          ;;
        n|N)
          tput cuu1;tput el
          break
          ;;
        *)
          tput cuu1;tput el
          ;;
      esac
    done
  done

  NSL_AFT=$(ls /var/hasplm/installed/68704/*.v2c 2>/dev/null | cut -f1 -d "_" | sort -u | wc -l)
  if test ${NSL_AFT} -ne ${NSL_BEF}
  then
    echo
    echo "Restarting license (aksusbd) service..."
    /usr/bin/systemctl restart aksusbd
  fi

  Press_Enter
}

#-------------------------------------------------------------------------------
# Menu display
#-------------------------------------------------------------------------------
disp_header

if test ! -x /usr/sbin/aksusbd
then
  echo
  echo "${FGORANGE}WARNING[0m: aksusbd is not installed (HASP license) !"
  echo
  Press_Enter
  exit 1
fi

UPDATE_EXE="hasp_update"

if test -s ${CHARONDIR}/bin/${UPDATE_EXE}
then
  test -x ${CHARONDIR}/bin/${UPDATE_EXE} || chmod u+x ${CHARONDIR}/bin/${UPDATE_EXE}
else
  echo >>${CHARONDIR}/log/$(basename $0).log
  echo $(date +"%d-%b-%Y %H:%M:%S") "------------------------------" >>${CHARONDIR}/log/$(basename $0).log

  echo "${UPDATE_EXE} executable file not found."
  echo "${UPDATE_EXE} executable file not found." >>${CHARONDIR}/log/$(basename $0).log

  LASTLOC=$(cat ${HOME}/.charonkitfolder 2>/dev/null)
  if test -n "${LASTLOC}"
  then
    echo "Searching for executable file in the kits folder..."
    TMP=$(find ${LASTLOC} -name ${UPDATE_EXE} | tail -1)
    if test -n "${TMP}"
    then
      echo "Found: ${TMP}"
      echo "Copying to ${CHARONDIR}/bin ..."
      cp ${TMP} ${CHARONDIR}/bin
      RET=$?
      if test ${RET} = 0
      then
        chmod u+x ${CHARONDIR}/bin/${UPDATE_EXE}
        echo "Done."
        echo "${UPDATE_EXE} executable copied to ${CHARONDIR}/bin" >>${CHARONDIR}/log/$(basename $0).log
      else
        echo "Failed to copy, error code ${RET}"
        echo "Failed to copy ${UPDATE_EXE} executable to ${CHARONDIR}/bin, error code ${RET}" >>${CHARONDIR}/log/$(basename $0).log
      fi
    else
      echo "Not found."
      echo "${UPDATE_EXE} executable not found in ${LASTLOC}" >>${CHARONDIR}/log/$(basename $0).log
    fi
  else
    echo "Cannot copy ${UPDATE_EXE} executable. No last location" >>${CHARONDIR}/log/$(basename $0).log
  fi
  sleep 2
fi

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

while test 1
do
  disp_header
  display_licfound
  tput bold
  echo "Available options:"
  LICFOLDER=$(cat ${CHARONLICFOLDER} 2>/dev/null)

  tput sgr0
  test -n "$(which firefox 2>/dev/null)" -a -n "${DISPLAY}" && tput bold
  echo -n "1"
  tput sgr0
  echo " - Use Firefox for license update/install (GUI)"
  echo

  NBV2C=0
  if test -n "${LICFOLDER}"
  then
    if test -d ${LICFOLDER}
    then
      NBV2C=$(ls ${LICFOLDER}/*.v2c 2>/dev/null | wc -l)
    fi
  fi
  tput bold
  test ${NBV2C} = 0 && tput sgr0
  echo -n "2"
  tput sgr0
  echo " - Install or update license using the Character User Interface (CUI)"

  tput bold
  echo -n "3"
  tput sgr0
  if test -n "${LICFOLDER}"
  then
    if test -d ${LICFOLDER}
    then
      echo " - Change license files folder [${FGBLUE}${LICFOLDER}[0m]"
      tput bold
      test ${NBV2C} = 0 && tput sgr0
      echo -n "4"
      tput sgr0
      echo " - Delete license files (.v2c) older than 'n' days"
    else
      echo " - Change license files folder [[31m${LICFOLDER}[0m]"
      echo "    [31m[1mThis folder does not exist![0m"
    fi
  else
    echo " - Set license files folder"
  fi
  echo

  test $(ls /var/hasplm/installed/68704/*.v2c 2>/dev/null | cut -f1 -d "_" | sort -u | wc -l) -gt 0 && tput bold
  echo -n "5"
  tput sgr0
  echo " - Remove a software license"
  echo

  tput bold
  echo -n "6"
  tput sgr0
  echo -n " - Update license description file "
  if test -e ${DONGLESFILE}
  then
    DFE=$(grep -v ^# ${DONGLESFILE} 2>/dev/null | wc -l)
    case ${DFE:-0}
    in
      0) echo "(empty)";;
      1) echo "(${DFE} entry)";;
      *) echo "(${DFE} entries)";;
    esac
  else
    echo "(empty)"
  fi
  echo

  echo "q - quit"
  echo

  while test 1
  do
    echo -n "Enter your choice: "
    read ANS
    case "${ANS}"
    in
      1)
        if test -n "$(which firefox 2>/dev/null)"
        then
          if test -n "${DISPLAY}"
          then
            use_gui
            break
          else
            echo "This option is not available: no DISPLAY defined"
            Press_Enter
            break
          fi
        else
          echo "This option is not available: firefox is not installed"
          Press_Enter
          break
        fi
        ;;          
      2)
        if test -x ${CHARONDIR}/bin/${UPDATE_EXE}
        then
          if test -z "${LICFOLDER}"
          then
            tput bold
            echo "Please define the license files folder first, option 3"
            tput sgr0
            Press_Enter
          else
            apply_v2c_file
          fi
        else
          echo "This option is not available: ${UPDATE_EXE} is not installed"
          Press_Enter
        fi
        break
        ;;
      3)
        echo
        while test 1
        do
          LICFOLDER=$(cat ${CHARONLICFOLDER} 2>/dev/null)
          echo -n "Enter the folder name [${LICFOLDER}] (q to quit): "
          read ANS
          test "${ANS}" = "q" -o -z "${ANS}" && break
          if test -d ${ANS}
          then
            if test -n "$(echo ${ANS} | tr -dc '_')"
            then
              echo "The underscore character '_' is not allowed. Please select another folder"
              Press_Enter
            else
              echo ${ANS} >${CHARONLICFOLDER}
              break
            fi
          else
            echo "This does not correspond to an existing folder."
            Press_Enter
          fi
        done
        break
        ;;
      4)
        if test -n "${LICFOLDER}"
        then
          if test -d ${LICFOLDER}
          then
            if test $(ls ${LICFOLDER} 2>/dev/null | wc -l) -gt 0
            then
              echo "${FGBLUE}License folder content (${LICFOLDER}):[0m"
              find ${LICFOLDER}/*.v2c -printf "%f - %Ad-%Ab-%AY %AH:%AM\n" | sort
              echo
              while test 1
              do
                echo -n "${FGBLUE}Delete .v2c and .txt files older than 'n' days ? [365] (q to quit):[0m "
                read ANS
                test "${ANS}" = "q" && break
                test -z "${ANS}" && ANS=365
                if test -n "$(echo ${ANS} | tr -d [:digit:])"
                then
                  echo "Must be numeric!"
                else
                  find ${LICFOLDER} \( -name '*.v2c' -o -name '*.txt' \) -mtime +${ANS} -exec rm -fv {} \;
                  sleep 2
                  break
                fi
              done
            else
              echo "${FGORANGE}No .v2c file found in the folder...[0m"
              Press_Enter
            fi
          fi
        fi
        break
        ;;
      5)
        if test $(ls /var/hasplm/installed/68704/*.v2c 2>/dev/null | cut -f1 -d "_" | sort -u | wc -l) -gt 0
        then
          remove_sl
          break
        else
          echo "This option is not available: no software license found"
          Press_Enter
          break
        fi
        ;;
      6)
        if test ! -e ${DONGLESFILE}
        then
          echo "#--- License description file -----------------------"  >${DONGLESFILE}
          echo "# Format: <license number>;<Description>;<Color code>" >>${DONGLESFILE}
        fi
        ask_editor noquit
        if test -n "${EDI}"
        then
          if test -z "`echo ${EDI}|grep vim`"
          then
            ${EDI} ${DONGLESFILE} 2>/dev/null
          else
            ${EDI} -u ${CHARONDIR}/utils/charonscript.vimrc ${DONGLESFILE} 2>/dev/null
          fi
        fi
        break
        ;;
      q)
        break 2
        ;;
      *)
        tput cuu1;tput el
        ;;
    esac
  done
done

exit
