#!/bin/sh
#-------------------------------------------------------------------------------
# charon_menu_setup.sh
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2022 STROMASYS.
# All rights reserved.
#
#set -x
VERSION=2.18

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

if test `id -u` -ne 0
then
  echo "Must be root !"
  echo
  exit 1
fi

if test -x /usr/bin/dnf
then
  alias yumc="/usr/bin/dnf --nogpgcheck"
  YUMM="dnf"
else
  alias yumc="/usr/bin/yum --nogpgcheck"
  YUMM="yum"
fi

#=============================================================================
# Function: select_kit_location
#=============================================================================
function select_kit_location
{
  echo
  KIT=""
  while test 1
  do
    LASTLOC=`cat ${HOME}/.charonkitfolder 2>/dev/null`
    LASTLOCDISP=""
    test -n "${LASTLOC}" && LASTLOCDISP="[${LASTLOC}] "
    echo "Enter kit location (folder), . for current folder, q to quit"
    echo -n "${LASTLOCDISP}: ${FGBLUE}"
    read KITLOC
    tput sgr0
    test -z "${KITLOC}" && KITLOC=${LASTLOC}
    test "${KITLOC}" = "." && KITLOC=${PWD}
    test "${KITLOC}" = "q" && break
    if test -n "${KITLOC}" -a -d "${KITLOC}"
    then
      >/tmp/charon_install.tmp

      #--- First pass: extract complete packs if there are
      echo
      echo "Searching for complete packs in ${KITLOC} ..."
      SAVKITLOC=${KITLOC}
      find ${KITLOC} -name "CHARON-*-completepack.tar.gz" | while read FILE
      do
        cd ${KITLOC}

        if test -s ${FILE}.md5sum
        then
          FILSUM=`cat ${FILE}.md5sum | awk '{print $1}'`
          DNLSUM=`md5sum ${FILE} | awk '{print $1}'`
          if test "${FILSUM}" = "${DNLSUM}"
          then
            echo "Unzipping complete pack '${FILE}' (MD5SUM match)"
            PACKIT=`tar -tzf ${FILE} | grep InstallationKit/$`
            tar -xzf ${FILE}
            test $? = 0 && mv ${FILE} ${FILE}.save
          else
            echo "[46m[30m WARNING [0m Cannot unzip complete pack '${FILE}': MD5SUM does not match"
          fi
        else
          echo "Unzipping complete pack '${FILE}'"
          tar -xzf ${FILE}
          if test $? = 0
          then
            mv ${FILE} ${FILE}.save
            mv ${PACKIT}/*.tar.gz* ${KITLOC} 
            echo "Files moved to '${KITLOC}' container" >${PACKIT}/readme.txt
          fi
        fi
      done
      echo "Done."
      echo

      #--- 2nd pass: search for kits
      printf "Searching kits in ${KITLOC} ..."
      find ${KITLOC} -name "charon-*.${INS_OS}*" -type d | while read FILE
      do
        printf "."
        echo ${FILE} >>/tmp/charon_install.tmp
      done
      find ${KITLOC} -name "charon-*.${INS_OS}*.tar" | while read FILE
      do
        printf "."
        echo ${FILE} >>/tmp/charon_install.tmp
      done
      find ${KITLOC} -name "charon-*.${INS_OS}*.tar.gz" | while read FILE
      do
        printf "."
        echo ${FILE} >>/tmp/charon_install.tmp
      done

      echo
      tput cuu1;tput el
      if test -s /tmp/charon_install.tmp
      then
        sort /tmp/charon_install.tmp >/tmp/charon_install.sort.tmp
        mv -f /tmp/charon_install.sort.tmp /tmp/charon_install.tmp
        while test 1
        do
          typeset -i I=0
          echo
          tput bold
          echo "No  Product              Version Build  Installed Container  md5sum"
          tput sgr0
          LAST_BLD=""

          ( cat /tmp/charon_install.tmp | while read LINE
          do
            if test -n "`echo ${LINE} | grep '\.${VENDOR_ID}\.'`"
            then
              #--- Vendor number is present in kit name
              echo ${LINE} | sed "s=\(^.*-\)\([0-9][0-9][0-9][0-9][0-9]\)\(\.${VENDOR_ID}\..*$\)=\2 \0=g"
            else
              #--- Vendor number is present in kit name
              echo ${LINE} | sed "s=\(^.*-\)\([0-9][0-9][0-9][0-9][0-9]\)\(\..*$\)=\2 \0=g"
            fi
          done ) | sort -n >/tmp/charon_install.tmp.sorted

          cat /tmp/charon_install.tmp.sorted | awk '{print $2}' >/tmp/charon_install.tmp

          cat /tmp/charon_install.tmp | while read LINE
          do
            I=I+1
            LKIT=`basename ${LINE}`
            LK3=`echo ${LKIT} | cut -f3 -d'-'`
            if test -z "`echo ${LK3} | tr -dc '.'`"
            then
              LPRD=`echo ${LKIT} | cut -f1 -d'-'`-`echo ${LKIT} | cut -f2 -d'-'`-`echo ${LKIT} | cut -f3 -d'-'`
              LVER=`echo ${LKIT} | cut -f4 -d'-'`
              LBLD=`echo ${LKIT} | cut -f5 -d'-' | cut -f1 -d'.'`
            else
              LPRD=`echo ${LKIT} | cut -f1 -d'-'`-`echo ${LKIT} | cut -f2 -d'-'`
              LVER=`echo ${LKIT} | cut -f3 -d'-'`
              LBLD=`echo ${LKIT} | cut -f4 -d'-' | cut -f1 -d'.'`
            fi
            LMD5="-"
            LINS="no"
            if test -d ${LINE}
            then
              LCNT="folder"
              LPK=`ls ${LINE}/charon-*base*.rpm 2>/dev/null`
              if test -z "${LPK}"
              then
                #-- V4.7+
                LPK=`ls ${LINE}/charon-axp-*.rpm ${LINE}/charon-vax-*.rpm 2>/dev/null`
                LPK=`rpm -q -p ${LPK}`
                test -z "`rpm -q ${LPK} 2>/dev/null | grep 'is not installed'`" && LINS="yes"
              else
                LPK=`rpm -q -p ${LPK}`
                if test -z "`rpm -q ${LPK} 2>/dev/null | grep 'is not installed'`"
                then
                  #-- V4.6- : check if charon-axp* or charon-vax* is installed
                  LPKT=`basename ${LINE} | cut -c1-11`
                  test -n "`rpm -q -a | grep ^${LPKT}`" && LINS="yes"
                fi
              fi
            else
              LCNT=`echo ${LINE} | sed "s=\(^.*\.\)\(tar.*$\)=\2=g"`
              if test "${LCNT}" = "tar.gz"
              then
                LINS="-"
                if test -e ${LINE}.md5sum
                then
                  FILSUM=`cat ${LINE}.md5sum | awk '{print $1}'`
                  DNLSUM=`md5sum ${LINE} | awk '{print $1}'`
                  if test "${FILSUM}" = "${DNLSUM}"
                  then
                    LMD5="[30m[42m OK [0m"
                  else
                    LMD5="[37m[41m FAILED [0m"
                  fi
                else
                  LMD5="not found"
                fi
              fi
            fi
            if test "${LAST_BLD}" != "${LBLD}"
            then
              if test "${SEMIGRAPH}" = "enabled"
              then
                tput smacs
                echo "qqq qqqqqqqqqqqqqqqqqqqq qqqqqqq qqqqqq qqqqqqqqq qqqqqqqqqq qqqqqqq"
                tput rmacs
              else
                echo "--- -------------------- ------- ------ --------- ---------- -------"
              fi
            fi
            test "${LINS}" = "no" && echo -n "${FGBLUE}"
            printf "%3d %-20s %7s %6s " $I ${LPRD} ${LVER} ${LBLD}
            test "${LINS}" = "yes" && echo -n "[32m[1m"
            printf "%-9s " ${LINS}
            test "${LINS}" = "yes" && echo -n "[0m"
            printf "%-10s " ${LCNT}
            echo "${LMD5}"
            tput sgr0
            LAST_BLD=${LBLD}
          done
          echo
          printf "Select the kit you want to use (q to quit): "
          read ANS
          test "${ANS}" = "q" && break 2
          echo
          if test -n "${ANS}"
          then
            if test -z "`echo ${ANS} | tr -d [0123456789]`"
            then
              if test ${ANS} -lt 1 -o ${ANS} -gt `cat /tmp/charon_install.tmp | wc -l`
              then
                tput bold
                echo "Incorrect value, out of range."
                tput sgr0
              else
                KIT=`cat /tmp/charon_install.tmp | head -${ANS} | tail -1`
                KITLOC=`dirname ${KIT}`
                KIT=`basename ${KIT}`
                echo "${SAVKITLOC}" >${HOME}/.charonkitfolder
                if test -n "`echo ${KIT} | grep '\.tar.gz$'`"
                then
                  cd ${KITLOC}
                  if test -s ${KIT}.md5sum
                  then
                    echo "Checking ${KIT} file (md5sum) ..."
                    FILSUM=`cat ${KIT}.md5sum | awk '{print $1}'`
                    DNLSUM=`md5sum ${KIT} | awk '{print $1}'`
                    if test "${FILSUM}" = "${DNLSUM}"
                    then
                      echo "Success."
                    else
                      echo "[41m[37mChecksum failure![0m Please remove the kit and download again."
                      KIT=""
                      Press_Enter
                      break 2
                    fi
                  fi
                  echo "Unzipping file..."
                  gunzip ${KIT}
                  KIT=`echo ${KIT} | sed "s=\.gz$==g"`
                  cd - >/dev/null 2>&1
                fi
                if test -n "`echo ${KIT} | grep '\.tar$'`"
                then
                  echo "Extracting tar file..."
                  cd ${KITLOC}
                  tar -xf ${KIT}
                  if test $? = 0
                  then
                    echo "Done."
                    KIT0=`tar -tf ${KIT} | head -1`
                    echo "Removing tar file..."
                    rm -f ${KIT}
                    KIT=`basename ${KIT0}`
                  else
                    tput bold
                    echo "Failed!"
                    tput sgr0
                    KIT=""
                  fi
                  cd - >/dev/null 2>&1
                fi
                break 2
              fi
            else
              tput bold
              echo "Incorrect value '${ANS}', must be numeric."
              tput sgr0
            fi
          fi
        done
        break
      else
        echo "[35mNo kit found in this folder!"
        tput sgr0
      fi
    else
      echo "[46m[30m WARNING [0m Invalid answer or '${KITLOC}' is not a folder"
      echo
    fi
  done
  echo
}

#=============================================================================
# Function: select_softlic_location
#=============================================================================
function select_softlic_location
{
  echo
  LIC=""
  while test 1
  do
    LASTLOC=`cat ${HOME}/.charonsoftlicfolder 2>/dev/null`
    LASTLOCDISP=""
    test -n "${LASTLOC}" && LASTLOCDISP="[${LASTLOC}] "
    echo "Enter software license location (folder), . for current folder, q to quit"
    printf "${LASTLOCDISP}: "
    read LICLOC
    test -z "${LICLOC}" && LICLOC=${LASTLOC}
    test "${LICLOC}" = "." && LICLOC=${PWD}
    test "${LICLOC}" = "q" && break
    if test -n "${LICLOC}"
    then
      >/tmp/charon_install.tmp
      printf "Searching license in ${LICLOC} ..."
      for SEARCH in  "dinst" "*HASP*.tar"
      do
        find ${LICLOC} -name ${SEARCH} | while read FILE
        do
          printf "."
          echo ${FILE} >>/tmp/charon_install.tmp
        done
      done
      echo
      tput cuu1;tput el
      if test -s /tmp/charon_install.tmp
      then
        while test 1
        do
          typeset -i I=0
          echo
          echo "[44m[37mLicense kits found[0m"
          cat /tmp/charon_install.tmp | while read LINE
          do
            I=I+1
            printf "%2d - " $I
            echo ${LINE}
          done
          echo
          printf "Select the kit you want to use (q to quit): "
          read ANS
          test "${ANS}" = "q" && break 2
          if test -n "${ANS}"
          then
            if test -z "`echo ${ANS} | tr -d [0123456789]`"
            then
              if test ${ANS} -lt 1 -o ${ANS} -gt `cat /tmp/charon_install.tmp | wc -l`
              then
                tput bold
                echo "Incorrect value, out of range."
                tput sgr0
              else
                LIC=`cat /tmp/charon_install.tmp | head -${ANS} | tail -1`
                LICLOC=`dirname ${LIC}`
                LIC=`basename ${LIC}`
                if test -z "`echo ${LIC} | grep '\.tar$'`"
                then
                  echo "${LICLOC}" >${HOME}/.charonsoftlicfolder
                else
                  echo "Extracting tar file..."
                  cd ${LICLOC}
                  tar -xf ${LIC}
                  if test $? = 0
                  then
                    echo "Done."
                    LIC=`tar -tf ${LIC} | head -1`
                    LIC=`dirname ${LIC}`
                    echo "${LICLOC}/${LIC}" >${HOME}/.charonsoftlicfolder
                  else
                    tput bold
                    echo "Failed!"
                    tput sgr0
                    LIC=""
                  fi
                  cd - >/dev/null 2>&1
                fi
                break 2
              fi
            else
              tput bold
              echo "Incorrect value '${ANS}', must be numeric."
              tput sgr0
            fi
          fi
        done
        break
      else
        echo "[35mNo kit found in this folder!"
        tput sgr0
      fi
    fi
  done
  echo
}

#=============================================================================
# Function: charon_install
#=============================================================================
function charon_install
{
  cd $1
  rpm -q glibc.i686 >/dev/null 2>&1
  if test $? != 0
  then
    echo "[46m[30m WARNING [0m 'glibc.i686' is not installed. Cannot continue."
    echo "          Please install it manually before continuing"
    echo
    return 1
  fi

  WEBUIRPM=`ls charon*webui*.rpm 2>/dev/null`
  if test -n "${WEBUIRPM}"
  then
    while test 1
    do
      echo -n "Do you want to install WEBUI (y/n) ? "
      read ANS
      case "${ANS}"
      in
        y|Y)
          break
          ;;
        n|N)
          mv -f ${WEBUIRPM} ${WEBUIRPM}.not_required
          break
          ;;
        *)
          tput cuu1;tput el
          ;;
      esac
    done
  fi

  #--- charon-ncu package for V4.6 cannot be installed on Red Hat 7+
  NCURPM=`ls charon-ncu*.rpm 2>/dev/null`
  if test "`cat ${OS_RELEASE} | awk '{print $1}'`" = "Red"
  then
    if test `cat ${OS_RELEASE} | sed "s=\(^.* release \)\(.*\)\( .*$\)=\2=g"|cut -f1 -d.` -ge 7
    then
      test -n "${NCURPM}" && mv -f ${NCURPM} ${NCURPM}.not_supported
    fi
  fi

  if test "`cat ${OS_RELEASE} | awk '{print $1}'`" = "Red"
  then
    if test `cat ${OS_RELEASE} | sed "s=\(^.* release \)\(.*\)\( .*$\)=\2=g"|cut -f1 -d.` -eq 7
    then
      if test -n "`ls charon-???-4.10-*.rpm 2>/dev/null`"
      then
        if test -z "`rpm -q -a | grep libev-`"
        then
          if test -n "`yum repolist rhel-7-server-extras-rpms | grep -w disabled`"
          then
            echo "[46m[30m WARNING [0m libev package is required with Charon-AXP/VAX V4.10."
            echo "          This package is not installed and the repository"
            echo "          'rhel-7-server-extras-rpms' is not enabled."
            echo "          If the installation fails, please run the command:"
            echo "          # `tput bold`yum-config-manager --enable rhel-7-server-extras-rpms`tput sgr0`"
            echo "          and restart the Charon installation"
            echo
            sleep 3
          fi
        fi
      fi
    fi
  fi

  YDAT=`date +%Y%m%d_%H%M%S`
  test ! -e ${CHARONDIR}/log && mkdir -p ${CHARONDIR}/log
  (yumc -y install *.rpm 2>&1;echo $? >/tmp/charon_setup.ret) | tee ${CHARONDIR}/log/${YUMM}.install.${YDAT}
  RET=`cat /tmp/charon_setup.ret 2>/dev/null`
  if test ${RET} = 0
  then
    #--- For case where install is OK but "Failed to" messages are found
    if test -n "`grep 'Failed to' ${CHARONDIR}/log/${YUMM}.install.${YDAT}`"
    then
      echo "[46m[30m Installation completed with failures [0m"
    else
      echo "[42m[30m Installation completed [0m"
    fi

    KITBLD=`rpm -q -a | grep charon | cut -f2 -d'.' | cut -f2 -d'-' | sort -u`
    if test ${KITBLD:-0} -ge 20400
    then
      tput smacs
      echo "lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk"
      echo -n "x "
      tput rmacs
      tput bold
      echo -n "It is recommended to reboot your Linux server after installation "
      tput sgr0
      tput smacs
      echo "x"
      echo "mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj"
      tput rmacs
      tput sgr0
    fi
  else
    echo "[41m[30m Installation failed (error code ${RET}) [0m"
  fi
  tput sgr0
  echo
  echo "${FGBLUE}Output saved to[0m [1m${CHARONDIR}/log/${YUMM}.install.${YDAT}[0m"

  test -e ${WEBUIRPM}.not_required && mv -f ${WEBUIRPM}.not_required ${WEBUIRPM}

  if test -e ${NCURPM}.not_supported
  then
    mv -f ${NCURPM}.not_supported  ${NCURPM}
    echo
    echo "Do you want to install 'ncu', this requires the 'tunctl' package to be"
    while test 1
    do
      echo -n "installed (y/n) ? "
      read ANS
      case "${ANS}"
      in
        y)
          yumc -y install ${NCURPM}
          RET=$?
          if test ${RET} = 0
          then
            echo "[42m[30m Installation completed [0m"
          else
            echo "[41m[30m Installation failed (error code ${RET}) [0m"
          fi
          tput sgr0
          break
          ;;
        n)
          break
          ;;
        *)
          tput cuu1;tput el
          ;;
      esac
    done
  fi

  cd - >/dev/null 2>&1
  echo
}

#=============================================================================
# Function: charon_uninstall
#=============================================================================
function charon_uninstall
{
  VMRUN=`ps -eo command|grep charon | grep '\-d' | grep cfg$`
  if test -n "${VMRUN}"
  then
    echo
    tput bold
    echo "Cannot uninstall Charon, at least a virtual machine is running:"
    tput sgr0
    echo ${VMRUN}
    echo
    return
  fi

  #--- Removing kits
  # before V4.7
  KITSLIST=`rpm -q -a | grep -w ^charon | grep -w -e base`
  # starting V4.7
  test -z "${KITSLIST}" && KITSLIST=`rpm -q -a | grep -e ^charon-axp- -e ^charon-vax-`

  for KIT in ${KITSLIST}
  do
    if test -n "`echo ${KIT} | grep -w base`"
    then
      KITNAM=`echo ${KIT} | sed "s=\(^.*base\)-\(.*$\)=\1=g"`
      KITRPM=${KIT}
      P=`rpm -q ${KITRPM} | grep -v 'not installed' | sed "s=\(^charon.*base-\)\(.*\)\(-\)\(.*\)\(\..*$\)=V\2 B\4=g"`
      KITBLD=`echo ${KIT} | sed "s=\(^.*base-.*-\)\(.*\)\(\..*$\)=\2=g"`
    else
      #-- For V4.7+
      KITNAM=`echo ${KIT} | cut -c1-10`
      KITRPM=${KIT}
      P=`rpm -q ${KITRPM} | grep -v 'not installed' | sed "s=\(^charon-[a-z][a-z][a-z]-\)\(.*\)\(-\)\(.*\)\(\..*$\)=V\2 B\4=g"`
      KITBLD=`echo ${KIT} | sed "s=\(^charon-[a-z][a-z][a-z]-.*-\)\(.*\)\(\..*$\)=\2=g"`
    fi
    if test -n "${P}"
    then
      echo
      echo "[31m[1mNotes[0m:[1m - Removing a base product will remove all related packages"
      echo "       - Please ensure there are no related virtual machines running before"
      echo "         uninstallation"
      echo "       - Starting with V4.6 B16603 and before V4.7 B17101, if both CHARON-VAX"
      echo "         and CHARON-AXP are installed, both will have to be removed"
      echo "[0m"
      while test 1
      do
        echo -n "Do you want to uninstall ${FGBLUE}${KITNAM} ${P}[0m (y/n) ? "
        read ANS
        case "${ANS}"
        in
          y|Y)
            echo
            echo "[44m[37m Removing ${KITRPM} ... [0m"
            sleep 1
            yumc -y remove ${KITRPM}
            if test ${KITBLD} -lt 16803
            then
              #--- Before V4.6 Build 16803
              case "${KITNAM}"
              in
                "charon-base")
                  echo "[44m[37m Removing charon-hasp ... [0m"
                  sleep 1
                  yumc -y remove charon-hasp
                  ;;
                "charon-axp-base")
                  echo "[44m[37m Removing charon-axp-utils ... [0m"
                  sleep 1
                  yumc -y remove charon-axp-utils

                  if test -n "`rpm -q -a | grep ^charon-axp-webui`"
                  then
                    echo "[44m[37m Removing charon-axp-webui ... [0m"
                    sleep 1
                    yumc -y remove charon-axp-webui
                  fi
                  ;;
              esac
            else
              #--- Starting with V4.6 Build 16803 and before 17101
              if test ${KITBLD} -lt 17101
              then
                for PK in "charon-hasp" "charon-ncu"
                do
                  if test -z "`rpm -q ${PK} | grep 'is not installed'`"
                  then
                    echo "[44m[37m Removing ${PK} ... [0m"
                    sleep 1
                    yumc -y remove ${PK}
                  fi
                done
              else
                #--- Starting with V4.7 Build 17101
                # if at least charon-axp or charon-vax is remaining, do nothing
                # otherwise, remove charon-utils and charon-license
                KITREMAINING="charon-axp"
                test "${KITNAM}" = "charon-axp" && KITREMAINING="charon-vax"
                if test -n "`rpm -q ${KITREMAINING} | grep 'is not installed'`"
                then
                  for PK in "charon-utils" "charon-license"
                  do
                    if test -z "`rpm -q ${PK} | grep 'is not installed'`"
                    then
                      echo "[44m[37m Removing ${PK} ... [0m"
                      sleep 1
                      yumc -y remove ${PK}
                    fi
                  done
                  #--- Starting with V4.9 Build 19407
                  if test ${KITBLD} -ge 19407
                  then
                    PK="charon-mtd"
                    if test -z "`rpm -q ${PK} | grep 'is not installed'`"
                    then
                      echo "[44m[37m Removing ${PK} ... [0m"
                      sleep 1
                      yumc -y remove ${PK}
                    fi
                  fi
                  #--- Starting with V4.10 Build 20205
                  if test ${KITBLD} -ge 20205
                  then
                    PK="charon-psrtp"
                    if test -z "`rpm -q ${PK} | grep 'is not installed'`"
                    then
                      echo "[44m[37m Removing ${PK} ... [0m"
                      sleep 1
                      yumc -y remove ${PK}
                    fi
                  fi
                fi
              fi               
            fi
            break
            ;;
          n|N)
            break
            ;;
          *)
            tput cuu1;tput el
            ;;
        esac
      done
    fi
  done

  #--- If no product remaining, remove aksusbd ---
  typeset -i I=0
  for KIT in "charon-axp-base" "charon-base" "charon-axp" "charon-vax"
  do
    KITRPM=`echo ${KIT} | cut -f2 -d':'`
    P=`rpm -q ${KITRPM} | grep -v 'not installed'`
    test -n "${P}" && I=I+1
  done
  if test ${I} -eq 0
  then
    for PK in charon-utils charon-license aksusbd
    do
      if test -z "`rpm -q ${PK} | grep 'is not installed'`"
      then
        echo "[44m[37m Removing ${PK} ... [0m"
        sleep 1
        yumc -y remove ${PK}
      fi
    done
  fi
}

#=============================================================================
# Function: charon_softlic_install
#=============================================================================
function charon_softlic_install
{
  echo
  if test -n "`/usr/bin/lsusb | grep HASP`"
  then
    echo "[41mFound dongle connected[0m"
    /usr/bin/lsusb | grep HASP
    echo
    printf "Please remove the license dongle first!"
  else
    select_softlic_location 
    if test -n "${LIC}"
    then
      echo "Uninstalling aksusb drivers with no dependencies..."
      AKS=`/bin/rpm -q -a | grep aksusbd`
      if test -n "${AKS}"
      then
        echo "Found: ${AKS}"
        /bin/rpm -e --nodeps ${AKS}
        AKS=`/bin/rpm -q -a | grep aksusbd`
        if test -n "${AKS}"
        then
          tput bold
          echo "Failed to uninstall."
          tput sgr0
        else
          echo "Removed."
        fi
      else
        echo "aksusbd package is not installed."
      fi
      SOFTLICLOC=`cat ${HOME}/.charonsoftlicfolder 2>/dev/null`
      if test -n "${SOFTLICLOC}"
      then
        cd ${SOFTLICLOC}
        if test -x dinst
        then
          ./dinst
          echo "Seeking for license number..."
          LICENSENUM=`hasp_srm_view | grep "^The License Number"  | cut -f2 -d: | tr -d [:cntrl:] | tr -d " "`
          tput cuu1;tput el
          if test -n "${LICENSENUM}"
          then
            echo "License number: ${LICENSENUM}"
          else
            tput bold
            echo "Failed to get license number. Please check."
            tput sgr0
          fi
        else
          tput bold
          echo "Cannot find 'dinst' setup script. Please perform installation manually"
          tput sgr0
        fi
        cd - >/dev/null
      else
        tput bold
        echo "Failed to get software license folder. Please retry."
        tput sgr0
      fi
    fi
  fi
}

#=============================================================================
# Function: charon_softlic_uninstall
#=============================================================================
function charon_softlic_uninstall
{
  #--- If installed, remove software license
  SOFTLICLOC=`cat ${HOME}/.charonsoftlicfolder 2>/dev/null`
  if test -n "${SOFTLICLOC}"
  then
    echo
    while test 1
    do
      echo -n "Do you want to uninstall the software license (y/n) ? "
      read ANS
      case "${ANS}"
      in
        y|Y)      
          if test -x ${SOFTLICLOC}/dunst
          then
            echo "Uninstalling software license..."
            cd ${SOFTLICLOC}
            ./dunst
            if test $? = 0
            then
              echo "Done."
            else
              tput bold
              echo "Failed."
              tput sgr0
            fi
            cd - >/dev/null
          else
            tput bold
            echo "Cannot find 'dunst' script in folder '${SOFTLICLOC}'."
            echo "Please locate software license folder and uninstall manually."
            tput sgr0
          fi
          rm -f ${HOME}/.charonsoftlicfolder
          break
          ;;
        n|N)
          break
          ;;
        *)
          tput cuu1;tput el
          ;;
      esac 
    done
  else
    echo "Software license location not found."
    echo "Please install first or proceed manually."
    echo
  fi
}

#-----------------------------------------------------------------------------
# Main menu
#-----------------------------------------------------------------------------
while test 1
do
  get_preferences
  tput clear
  display_header "Install/Upgrade/Remove CHARON"
  echo -n "Hostname:            ${FGBLUE}"
  hostname
  tput sgr0
  echo -n "Linux version:       ${FGBLUE}"
  if test -e /etc/redhat-release
  then
    OS_RELEASE=/etc/redhat-release
  else
    OS_RELEASE=/etc/system-release
  fi
  cat ${OS_RELEASE}
  echo    "                     `uname -s` `uname -r`"
  tput sgr0
  echo

  if test "$1" = "el" -o "$1" = "fc"
  then
    INS_OS="$1"
  else
    case "`cat ${OS_RELEASE} | awk '{print $1}'`"
    in
      "Red")
         #--- Version selection (since V4.8)
         INS_MAJOR=`cat ${OS_RELEASE} | sed "s=\(^.* release \)\(.*\)\(\..*$\)=\2=g"`
         INS_OS="el${INS_MAJOR}"
         ;;
      "CentOS")
         #--- Version selection (since V4.8)
         INS_MAJOR=`cat ${OS_RELEASE} | sed "s=\(^.* release \)\(.\)\(.*$\)=\2=g"`
         INS_OS="el${INS_MAJOR}"
         ;;
      "Fedora")
         INS_OS="fc"
         ;;
      *)
         echo "Cannot determine which kit to use between Red Hat and Fedora. Please contact support!"
         sleep 2
         break
         ;;
    esac
  fi

  tput smul
  echo "Installed packages"
  tput rmul

  echo -n "- License driver:    "
  P=`rpm -q aksusbd | grep ^aksusbd`
  echo "${FGBLUE}${P:-[31mNot installed or Software license}"
  tput sgr0
  typeset -i I=0
  echo -n "- Base products:     "

  P=`rpm -q charon-axp-base | grep -v 'not installed' | sed "s=\(^charon.*base-\)\(.*\)\(-\)\(.*\)\(\..*$\)=V\2 B\4=g"`
  if test -n "${P}"
  then
    echo "${FGBLUE}charon-axp-base ${P}[0m"
    I=I+1
  fi
  P=`rpm -q charon-base | grep -v 'not installed' | sed "s=\(^charon.*base-\)\(.*\)\(-\)\(.*\)\(\..*$\)=V\2 B\4=g"`
  if test -n "${P}"
  then
    test ${I} -gt 0 && echo -n "                     "
    echo "${FGBLUE}charon-base ${P}[0m"
    I=I+1
  fi
  P=`rpm -q charon-axp | grep -v 'not installed' | sed "s=\(^charon-axp-\)\(.*\)\(-\)\(.*\)\(\..*$\)=V\2 B\4=g"`
  if test -n "${P}"
  then
    test ${I} -gt 0 && echo -n "                     "
    echo "${FGBLUE}charon-axp ${P}[0m"
    I=I+1
  fi
  P=`rpm -q charon-vax | grep -v 'not installed' | sed "s=\(^charon-vax-\)\(.*\)\(-\)\(.*\)\(\..*$\)=V\2 B\4=g"`
  if test -n "${P}"
  then
    test ${I} -gt 0 && echo -n "                     "
    echo "${FGBLUE}charon-vax ${P}[0m"
    I=I+1
  fi

  if test ${I} -eq 0
  then
    echo "[31mNo one installed[0m"
  else
    echo -n "- Packages :         ${FGBLUE}"
    typeset -i CNT=0
    #for EMU in `rpm -q -a | grep ^charon | grep -v -e base -e utils -e hasp -e ncu | sort | awk -F'-' '{print $2"/"$3}'`
    for EMU in `rpm -q -a | grep ^charon | sort | awk -F'-' '{print $2"/"$3}'`
    do
      CNT=CNT+1
      if test ${CNT} -gt 4
      then
        CNT=0
        echo ${EMU}
        echo -n "                     "
      else
        echo -n "${EMU} "
      fi
    done
    echo "[0m"
  fi

  tput sgr0
  echo
  tput smul
  tput bold
  echo -n "Note"
  tput rmul
  tput sgr0
  echo ": If you perform an upgrade uninstall the current build first"
  tput sgr0
  echo 

  CNT=${I}
  while test 1
  do
    echo -n "Enter your choice (i"
    test ${CNT} -gt 0 && echo -n "/u"
    echo -n "/r/s/q/?): "
    read ANS
    case "${ANS}"
    in
      i|I)
        select_kit_location

        if test -n "${KIT}"
        then
          echo
          echo "[31m[1mNotes[0m:[1m - Starting with V4.6 B16603, if you're installing both"
          echo "         CHARON-AXP and CHARON-VAX, they must be the same build number"
          echo "[0m"
          Press_Enter
          KITRPM=`ls ${KITLOC}/${KIT}/charon*base*.${VENDOR_ID}.*.rpm ${KITLOC}/${KIT}/charon-axp-*\.*-[0-9][0-9][0-9][0-9][0-9].*.rpm ${KITLOC}/${KIT}/charon-vax-*\.*-[0-9][0-9][0-9][0-9][0-9].*.rpm 2>/dev/null`
          if test -z "${KITRPM}"
          then
            echo "[41m[37m Error [0m"
            echo "Corrupted kit, no 'charon*base.rpm' nor 'charon-???-[0-9]*.rpm' file found."
          else
            charon_install ${KITLOC}/${KIT}

            if test $? = 0 -a -z "`echo ${PATH} | grep '/opt/charon'`"
            then
              if test "${SEMIGRAPH}" = "enabled"
              then
                X="`tput smacs`x`tput rmacs`"
                tput smacs
                echo "lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk"
                tput rmacs
              else
                X="|"
                echo "+--------------------------------------------------------------------------+"
              fi
              cat <<EOF
$X [31mPATH not set[0m, it is recommended to logoff and login before using CHARON  $X
$X or to leave the menu then run:                                           $X
$X                                                                          $X
$X # [1m. /etc/profile.d/charon_axp.sh[0m (for CHARON-AXP before V4.6)            $X
$X  and/or                                                                  $X
$X # [1m. /etc/profile.d/charon.sh[0m     (for CHARON-VAX & CHARON-AXP > V4.6)    $X
EOF
              if test "${SEMIGRAPH}" = "enabled"
              then
                tput smacs
                echo "mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj"
                tput rmacs
              else
                echo "+--------------------------------------------------------------------------+"
              fi
            fi
          fi
          Press_Enter
        fi
        break
        ;;
      u|U)
        charon_uninstall
        Press_Enter
        break
        ;;
      r|R)
        break
        ;;
      s|S)
        echo
        while test 1
        do
          echo -n "Do you want to install or uninstall software license key (i/u/q) ? "
          read ANS
          case "${ANS}"
          in
            i|I)
              charon_softlic_install
              Press_Enter
              break
              ;;
            u|U)
              charon_softlic_uninstall
              Press_Enter
              break
              ;;
            q|Q)
              break
              ;;
            *)
              tput cuu1;tput el
              ;;
          esac
        done
        break
        ;;
      q|Q)
        break 2
        ;;
      clean)
        while test 1
        do
          echo -n "Please confirm (y/n): "
          read ANS
          case "${ANS}"
          in
            y)
              for I in 1 2 3 4
              do
                rpm -q -a | grep ^charon | while read PK
                do
                  echo "[44m[37m Removing ${PK} ... [0m"
                  yumc -y remove ${PK}
                done
                rpm -q -a | grep ^aksusbd | while read PK
                do
                  echo "[44m[37m Removing ${PK} ... [0m"
                  yumc -y remove ${PK}
                done
              done
              break 2
              ;;
            n)
              break 2
              ;;
            *)
              tput cuu1;tput el
              ;;
          esac
        done
        ;;
      ?|h|H)
        cat <<EOF

`tput smul`Enter`tput rmul`:
  i      - to install or upgrade
  u      - to uninstall (available if a product is at least installed)
  r      - to reload the screen (refresh)
  s      - to install/uninstall Software license provided as a kit
  clean  - to remove all installed CHARON products
  q      - to quit
  ? or h - to display this message  
EOF
        Press_Enter
        break
        ;;
      *)
        tput cuu1;tput el
        ;;
    esac
  done
done

exit
