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

get_preferences

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

#-------------------------------------------------------------------------------
# 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")
        PLATFORMID=$(grep '<platform id=' ${LINE} | sed "s:^.*<platform id=\"\(.*\)\"></platform>.*:\1:g")
        test -n "${PLATFORMID}" && PLATFORMID="(${PLATFORMID})"
        printf "${LINECOL}%2d - %s - %s %s" ${N} $(basename ${LINE}) "${DISPDAT}" "${PLATFORMID}"
        echo "[0m"
        echo ${LINE} >>${TMPFIL}
      done
      echo
      if test $N -gt 0
      then
        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
        ALRSEL="X"
        for SEL in $(echo ${ANS} | tr "," " ")
        do
          if test -z "$(echo ${SEL} | tr -d [:digit:])"
          then
            if test -x ${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 '<charon_info>' '<charon>' '<platform id=' '</platform>' \
                             '<license id=' '</license>' '</charon>' \
                             '<v2c>' '</v2c>' '</charon_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"
                    ${UPDATE_EXE} -f ${LICFILE}
                    test $? -ne 0 && echo "[30m[41m ERROR [0m failed to apply license"
                    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 ${UPDATE_EXE} file!"
              echo >>${CHARONDIR}/log/$(basename $0).log
              echo $(date +"%d-%b-%Y %H:%M:%S") " Cannot execute ${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    
}

#-------------------------------------------------------------------------------
# Menu display
#-------------------------------------------------------------------------------
if test $(id -u) -ne 0
then
  disp_header
  echo
  echo "[31mERROR[0m: must be root !"
  exit 1
fi

UPDATE_EXE="/opt/license-server/v2c"
if test ! -x ${UPDATE_EXE}
then
  disp_header
  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."
  exit 2
fi

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

  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 "1"
  tput sgr0
  echo " - Install or update license (v2c)"

  tput bold
  echo -n "2"
  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 "3"
      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

  echo "q - quit"
  echo

  while test 1
  do
    echo -n "Enter your choice: "
    read ANS
    case "${ANS}"
    in
      1)
        if test -x ${UPDATE_EXE}
        then
          if test -z "${LICFOLDER}"
          then
            tput bold
            echo "Please define the license files folder first, option 2"
            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
        ;;
      2)
        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
        ;;
      3)
        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
        ;;
      q)
        break 2
        ;;
      *)
        tput cuu1;tput el
        ;;
    esac
  done
done

exit
