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

. `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 "hpa-*-l*" -type d | while read FILE
      do
        printf "."
        echo ${FILE} >>/tmp/charon_install.tmp
      done
      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 not is present in kit name
              if test "`basename ${LINE} | cut -c1-3`" = "hpa"
              then
                LINH=`ls ${LINE}/hpa-*.rpm`
                if test -n "${LINH}"
                then
                  LINH=`echo ${LINH} | sed "s=^${LINE}/==g" | sed "s=^hpa-.*-\([0-9][0-9][0-9][0-9][0-9]\)\..*$=\1=g"`
                  echo ${LINH} ${LINE}
                fi
              else
                echo ${LINE} | sed "s=\(^.*-\)\([0-9][0-9][0-9][0-9][0-9]\)\(\..*$\)=\2 \0=g"
              fi
            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}`

            if test "`echo ${LKIT} | cut -c1-3`" = "hpa"
            then
              LPRD="hpa"
              LVER=`echo ${LINE} | cut -f2 -d '-' | sed "s=\([0-9]\)\([0-9]\)=\1\.\2\.0=g"`
              LBLD="00000"
              LINH=`ls ${LINE}/hpa-*.rpm`
              if test -n "${LINH}"
              then
                LBLD=`echo ${LINH} | sed "s=^${LINE}/==g" | sed "s=^hpa-.*-\([0-9][0-9][0-9][0-9][0-9]\)\..*$=\1=g"`
              fi
            else
              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
            fi

            LMD5="-"
            LINS="no"
            if test -d ${LINE}
            then
              LCNT="folder"
              if test "`echo ${LKIT} | cut -c1-3`" = "hpa"
              then
                LPK=`ls ${LINE}/hpa-*.rpm 2>/dev/null`
              else
                LPK=`ls ${LINE}/charon-par-*.rpm 2>/dev/null | grep -v debuginfo`
              fi
              if test -n "${LPK}"
              then
                LPK=`rpm -q -p ${LPK}`
                if test -z "`rpm -q ${LPK} 2>/dev/null | grep 'is not installed'`"
                then
                  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: charon_install
#=============================================================================
function charon_install
{
  cd $1

#-------TODO: To confirm for RHEL 7 & 8
#  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
#      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

  YDAT=`date +%Y%m%d_%H%M%S`
  test ! -e ${CHARONDIR}/log && mkdir -p ${CHARONDIR}/log

#TODO
  #-- Try to resolve conflict is aksusbd packages for .i386 and .x86_64 are present (TO CONFIRM)
  if test `uname -m` = "x86_64"
  then
    if test -n "`ls aksusbd-*.x86_64.rpm 2>/dev/null`"
    then
      if test -n "`ls aksusbd-*.i386.rpm 2>/dev/null`"
      then
        ls aksusbd-*.i386.rpm 2>/dev/null | xargs -i mv {} {}.not_installed 2>/dev/null
      fi
    fi
  else
    ls aksusbd-*.x86_64.rpm 2>/dev/null | xargs -i mv {} {}.not_installed 2>/dev/null
  fi

  #-- Do not install the debuginfo. Only manual install
  if test -n "`ls charon-par-debuginfo*.rpm 2>/dev/null`"
  then
    ls charon-par-debuginfo*.rpm 2>/dev/null | xargs -i mv {} {}.not_installed 2>/dev/null
  fi

  if test "`basename $1 | cut -c1-3`" = "hpa"
  then
    (yumc -y install hpa-*.rpm *.${INS_OS}.*.rpm aksusbd*.rpm 2>&1;echo $? >/tmp/charon_setup.ret) | tee ${CHARONDIR}/log/${YUMM}.install.${YDAT}
  else
    (yumc -y install *.${INS_OS}.*.rpm aksusbd*.rpm 2>&1;echo $? >/tmp/charon_setup.ret) | tee ${CHARONDIR}/log/${YUMM}.install.${YDAT}
  fi
  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
    #--- If the /etc/profile.d/charon.sh file does not exist, create it
    if test ! -e /etc/profile.d/charon.sh
    then
      echo "PATH=\$PATH:/opt/charon/bin:/opt/charon/cfg" >/etc/profile.d/charon.sh
      echo "export PATH" >>/etc/profile.d/charon.sh
    fi
    if test -z "`echo $PATH | grep /opt/charon/bin`"
    then
      cat <<EOP
Execute the following command or disconnect/reconnect for PATH to be defined:

# . /etc/profile.d/charon.sh

EOP
    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"

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

#=============================================================================
# Function: charon_uninstall
#=============================================================================
function charon_uninstall
{
  VMRUN=`ps -eo command|grep -w -e [c]haron-par -e [h]ppa`
  if test -n "${VMRUN}"
  then
    echo
    tput bold
    echo "Cannot uninstall Charon, there is at least one virtual machine running:"
    tput sgr0
    echo ${VMRUN}
    echo
    return
  fi

  ANS="n"
  for KITNAM in "hpa" "charon-par" "charon-par-debuginfo" "charon-mtd" "charon-license" "aksusbd"
  do
    P=`rpm -q ${KITNAM} 2>/dev/null | grep "is not installed"`
    if test -z "${P}"
    then
      while test 1
      do
        if test "${KITNAM}" = "charon-par" -o "${KITNAM}" = "hpa"
        then
          echo -n "Do you want to uninstall ${FGBLUE}${KITNAM}[0m (y/n) ? "
          read ANS
        fi
        case "${ANS}"
        in
          y|Y)
            echo
            echo "[44m[37m Removing ${KITNAM} package ... [0m"
            sleep 1
            yumc -y remove ${KITNAM}
            break
            ;;
          n|N)
            break
            ;;
          *)
            tput cuu1;tput el
            ;;
        esac
      done
    fi
  done
}


#-----------------------------------------------------------------------------
# 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"
  then
    INS_OS="$1"
  else
    case "`cat ${OS_RELEASE} | awk '{print $1}'`"
    in
      "Red")
         INS_MAJOR=`cat ${OS_RELEASE} | sed "s=\(^.* release \)\(.*\)\(\..*$\)=\2=g"`
         INS_OS="el${INS_MAJOR}"
         ;;
      "CentOS")
         INS_MAJOR=`cat ${OS_RELEASE} | sed "s=\(^.* release \)\(.\)\(.*$\)=\2=g"`
         INS_OS="el${INS_MAJOR}"
         ;;
      *)
         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

  typeset -i I=0
  for EMU in `rpm -q -a | grep -e ^hpa -e ^charon -e ^aksusbd | sort`
  do
    P=`echo ${EMU} | sed -e "s=\.i386==g" -e "s=\.x86_64==g"`
    echo "- ${FGBLUE}${P}[0m"
    I=I+1
  done
  if test ${I} -eq 0
  then
    echo "[31mNo one installed[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/q/?): "
    read ANS
    case "${ANS}"
    in
      i|I)
        select_kit_location

        if test -n "${KIT}"
        then
          if test "`echo ${KIT} | cut -c1-3`" = "hpa"
          then
            KITRPM=`ls ${KITLOC}/${KIT}/hpa-*.rpm 2>/dev/null`
          else
            KITRPM=`ls ${KITLOC}/${KIT}/charon-par-*.rpm 2>/dev/null`
          fi
          if test -z "${KITRPM}"
          then
            echo "[41m[37m Error [0m"
            echo "Corrupted kit, no 'charon-par-*.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.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
        ;;
      q|Q)
        break 2
        ;;
      ?|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)
  q      - to quit
  ? or h - to display this message  
EOF
        Press_Enter
        break
        ;;
      *)
        tput cuu1;tput el
        ;;
    esac
  done
done

exit
