#!/bin/sh
#-------------------------------------------------------------------------------
#
#  Scriptname: deinstall                       Platform: all
#      Author: Michael van de Ven         Creation date: 01/07/1999
#
# Description: Toplevel deinstall script that detects the current platform and
#              starts the appropriate platform script.
#                         
#
# Copyright (c) 1998-2002 GEAR Software BV.
#
#-------------------------------------------------------------------------------



#
# REVISION LIST
#
# Revision             Author                   Date
#------------------------------------------------------------------------------
# 0.1 (creation)       Michael van de Ven       01/07/1999
# 0.2                  Jeffry Sleddens          09/08/1999



#
# VARIABLE DEFINITION
#
# Variable                      Description
#------------------------------------------------------------------------------
# A                             Temp variable for read command.
# ALLPLATFORMS                  Holds all uppercase platform names seperated
#                                 with a colon.
# ANSWER                        Temp variable that holds an answer.
# CWD                           Current workdir.
# DEFAULT                       Variable that holds a default value.
# DPACKS                        Holds packagenames (deinstallation-order).
# FUNCS                         Holds the filename of the platform funcs script.
# INSTALLED                     Holds packagenames that were found during a
#                                 search for installed packages.
# IPACKS                        Holds packagenames (installation-order).
# LOGFILE                       Variable that holds the logfile's filename.
# OSNAME                        Name of the OS returned by uname -s.
# OSVER                         Most significant part of the version of the OS
#                                 returned by uname -v. (only on AIX).
# OSREL                         Release version of the OS returned by uname -r.
# OSHW                          Architecture of the workstation. (only on Sun).
# PACKFULL                      Returned by getpackfullname ().
# PACKINFO                      Returned by getpackinfo ().
# PACKS                         Holds iterated packagenames.
# PLATFORM                      Lowercase platformname.
# PLATFORMDIR                   Directoryname of the platform.
# PLATFORMFULL                  Nice full and printable platformname.
# PRINTF                        Holds the command for single line print.
# PRODUCT                       Contains the productname and version.
# SCRIPTDIR                     Contains the root-scriptdir.
# STATUS                        Holds 'installed' or 'not found'.
# TMPDIR                        Holds rootdirectory of the temp-dir.
# TMPFILE                       Holds filename of the temp-file.
# USERID                        The uid of the user running deinstall.
#



#
# FUNCTION DEFINITION
#
# Function                      Description
#------------------------------------------------------------------------------
# cleantmp                      Removes the temp-file TMPFILE.
# createlog                     Create a new deinstallation log.
# createtmp                     Sets variables TMPDIR and TMPFILE.
# deinstallmenu                 Function that displays the deinstallmenu.
# deinstallopt                  Function that removes optional packages.
# deinstallpacks                Function that finally removes packages.
# deinstallreq                  Function that removes required packages.
# detectplatform                Determine current platform and store info in 
#                                 the variable $ID.
# echoc                         Printf replacement using echo "<text>\c".
# echon                         Printf replacement using echo -n "<text>".
# entertocontinue               Show the "Press <enter> to continue." message.
# getpackfullname               Returns the full package name.
# getpackinfo                   Returns extra package information.
# getpacks                      Returns an iteration of (de)installation-orders.
# getscriptdir                  Stores the directory in which this script was.
# getyesno                      Get a yes/no answer from the user.
# hr                            Displays a 80 char long line.
# mainmenu                      Function that displays the mainmenu.
# setprintf                     Decides which printf implementation is used.
# showstatus                    Function that displays the status of packages on
#                                 the system where the script is executed.
# viewlog                       View the deinstallation log.



#
# FUNCTION BLOCK
#------------------------------------------------------------------------------
#



cleantmp ()
{
  rm -f "${TMPFILE}"
} # end of cleantmp



createlog ()
{
  if [ -d "/tmp" ] ; then
    LOGFILE="/tmp/gear_deinstall.log"
  else  
    LOGFILE="/gear_deinstall.log"
  fi
  if [ -f "${LOGFILE}" ] ; then
    mv "${LOGFILE}" "${LOGFILE}.old"
  fi
  echo "" > "${LOGFILE}"
  echo "  Install ${PRODUCT} on ${PLATFORMFULL} - Deinstallation log" >> "${LOGFILE}"
  hr >> "${LOGFILE}"
  echo "" >> "${LOGFILE}"
  echo "  Logging started at `date`." >> "${LOGFILE}"
  echo "" >> "${LOGFILE}"
  export LOGFILE
} # end of createlog



createtmp ()
{
  if [ -d "/tmp" ] ; then
    TMPDIR="/tmp/"
    TMPFILE="/tmp/gear_deinstall.tmp"
  else  
    TMPDIR="/"
    TMPFILE="/gear_deinstall.tmp"
  fi
  : > "${TMPFILE}"
  export TMPDIR TMPFILE
} # end of createtmp



deinstallmenu ()
{
  while true ; do
    clear
    echo ""
    echo "  Deinstall ${PRODUCT} on ${PLATFORMFULL} - Deinstall Menu"
    hr
    echo ""
    echo "      1) Deinstall Required Packages"
    echo "      2) Deinstall Optional Packages"
    echo "      q) Return to Main Menu"
    echo ""
    echo ""
    "${PRINTF}" "  Your choice? : "
    read A

     case "${A}" in
      "1")
        deinstallreq
        : > "${TMPFILE}"
        deinstallmenu
        break
      ;;
      "2")
        deinstallopt
        : > "${TMPFILE}"
        deinstallmenu
        break
      ;;
      "q"|"r")
        return 0
      ;;
      default)
        deinstallmenu
        break
      ;;
    esac
  done
} # end of deinstallmenu



deinstallopt ()
{
  INSTALLED=""
  PACKS=`getpacks optdeinst`
  for PACK in `getpacks optdeinst | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    PACKINFO=`getpackinfo "${PACK}"`
    if [ "x`"${FUNCS}" checkpack "${PACKINFO}"`" = "xinstalled" ] ; then
      INSTALLED="${INSTALLED}${PACK}:"
    fi
  done

  clear
  echo ""
  echo "  Deinstall ${PRODUCT} on ${PLATFORMFULL} - Optional packages"
  hr
  echo ""
  if [ "x${INSTALLED}" = "x" ] ; then
    echo "  None of the optional packages have been found on your system."
    echo ""
    entertocontinue
    return 0
  fi
  if [ "x${INSTALLED}" != "x" ] ; then
    echo "  The following optional packages have been found on your system:"
    echo ""
    for PACK in `echo "${PACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
      PACKINFO=`getpackinfo "${PACK}"`
      if [ "x`"${FUNCS}" checkpack "${PACKINFO}"`" = "xinstalled" ] ; then
        echo "    `getpackfullname "${PACK}"`"
      fi
    done
    echo ""
    echo "  It is allowed that these are to be removed."
    echo ""
    printf "  Do you want to continue? (y/n) [n]: "
    getyesno n
    if [ "x${ANSWER}" = "xn" ] ; then
      return 0
    fi
    deinstallpacks "${INSTALLED}"
  fi
  return 0
} # end of deinstallopt



deinstallpacks ()
{
  DPACKS="$*"
  clear
  echo ""
  echo "  Deinstall ${PRODUCT} on ${PLATFORMFULL} - Deinstallation progress"
  hr
  echo ""
  for PACK in `echo "${DPACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    PACKFULL=`getpackfullname "${PACK}"`
    "${PRINTF}" "  Deinstalling old ${PACKFULL} ... "
    PACKINFO=`getpackinfo "${PACK}"`
    "${FUNCS}" deinstallpack "${PACKINFO}"
    if [ "$?" -ne "0" ] ; then  # Uhoh, something went wrong.
      echo "failed"
    else
      echo "successful"
      if [ "x`echo ${PACKINFO} | awk -F':' '{print $3}'`" = "xinit" ] ; then
        INITPACKS="${INITPACKS}${PACK}:"
      fi
    fi
    echo ""
  done
  entertocontinue
} # end of deinstallpacks



deinstallreq ()
{
  INSTALLED=""
  PACKS=`getpacks reqdeinst`
  IPACKS=`getpacks reqinst`
  for PACK in `getpacks reqdeinst | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    PACKINFO=`getpackinfo "${PACK}"`
    if [ "x`"${FUNCS}" checkpack "${PACKINFO}"`" = "xinstalled" ] ; then
      INSTALLED="${INSTALLED}${PACK}:"
    fi
  done

  clear
  echo ""
  echo "  Deinstall ${PRODUCT} on ${PLATFORMFULL} - Required packages"
  hr
  echo ""
  if [ "x${INSTALLED}" = "x" ] ; then
    echo "  None of the required packages have been found on your system."
    echo ""
    entertocontinue
    return 0
  fi
  if [ "x${INSTALLED}" != "x" ] ; then
    echo "  The following required packages have been found on your system:"
    echo ""
    for PACK in `echo "${IPACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
      PACKINFO=`getpackinfo "${PACK}"`
      if [ "x`"${FUNCS}" checkpack "${PACKINFO}"`" = "xinstalled" ] ; then
        echo "    `getpackfullname "${PACK}"`"
      fi
    done
    echo ""
    echo "  It is allowed that these are to be removed."
    echo ""
    printf "  Do you want to continue? (y/n) [n]: "
    getyesno n
    if [ "x${ANSWER}" = "xn" ] ; then
      return 0
    fi
    deinstallpacks "${INSTALLED}"
  fi
  return 0
} # end of deinstallreq



detectplatform ()
{
  ALLPLATFORMS="solsparc:solx86:hpux:digital_unix:irix:aix:linux:unknown"

  OSNAME=`uname -s`; OSVER=`uname -v`; OSREL=`uname -r`; OSHW=`uname -m`

  case "${OSNAME}" in
    "Linux")
      case "${OSREL}" in
        2.*)
          PLATFORM="linux"
        ;;
      esac
    ;;
    "SunOS")
      case "${OSREL}" in
        5.6* | 5.7* | 5.8* | 5.9* )
          case "${OSHW}" in
            sun4*)
              PLATFORM="solsparc"
            ;;
            "i86pc")
              PLATFORM="solx86"
            ;;
            *)
              PLATFORM="unknown"
            ;;
            esac
        ;;
        *)
          PLATFORM="unknown"
        ;;
      esac
    ;;
    
    "HP-UX")
      case "${OSREL}" in
        *.10.* | *.11.*)
          PLATFORM="hpux"
        ;;
        *)
          PLATFORM="unknown"
        ;;
      esac
    ;;
  
    OSF*)
      case "${OSREL}" in
        *4* | *5* )
          PLATFORM="digital_unix"
        ;;
        *)
          PLATFORM="unknown"
        ;;
      esac
    ;;
  
    IRIX* | IRX* )
      case "${OSREL}" in
        "6.2" | "6.3" | "6.4" | "6.5")
          PLATFORM="irix"
        ;;
        *)
          PLATFORM="unknown"
        ;;
      esac
    ;;

    "AIX")
      case "${OSVER}.${OSREL}" in
        "4.1" | "4.2" | "4.3")
          PLATFORM="aix"
        ;;
        *)
          PLATFORM="unknown"
        ;;
      esac
    ;;
  
    *)
      PLATFORM="unknown"
    ;;
  esac

  clear

  #PLATFORM="unknown" # DEBUG
  if [ "x${PLATFORM}" = "xunknown" ] ;  then
      clear
      echo ""
      echo "  ${PRODUCT} deinstallation failure"
      hr
      echo ""
      echo "  Your (version of) operating system is not supported. Please visit our"
      echo "  website http://www.gearsoftware.com/ for more information regarding"
      echo "  our UNIX platform support."
      echo ""
      entertocontinue
      echo ""
      exit 0
  fi

  PLATFORMDIR="pltfrms/${PLATFORM}"
  export PLATFORMDIR
  FUNCS="funcs_${PLATFORM}"

  if [ ! -d "${SCRIPTDIR}/${PLATFORMDIR}" ] ; then
    PLATFORMDIR=`echo "${PLATFORMDIR}" | tr '[a-z]' '[A-Z]'`
  fi
  if [ ! -d "${SCRIPTDIR}/${PLATFORMDIR}" ] ; then
    clear
    echo "ERROR: Could not find platform specific section, quiting..."
    echo ""
    exit 1
  fi
  if [ ! -f "${SCRIPTDIR}/${PLATFORMDIR}/${FUNCS}" ] ; then
    FUNCS="`echo "${FUNCS}" | tr '[a-z]' '[A-Z]'`.;1"
  fi
  if [ ! -f "${SCRIPTDIR}/${PLATFORMDIR}/${FUNCS}" ] ; then
    clear
    echo "ERROR: Could not find platform specific script, quiting..."
    echo ""
    exit 2
  fi
  PLATFORMDIR="${SCRIPTDIR}/${PLATFORMDIR}"
  FUNCS="${PLATFORMDIR}/${FUNCS}"
} # end of detectplatform



echoc ()
{
  echo "${*}\c"
} # end of echoc



echon ()
{
  echo -n "${*}"
} # end of echon



entertocontinue ()
{
  echo ""
  "${PRINTF}" "  Press <enter> to continue."
  read A
} # end of entertocontinue



getpackfullname ()
{
  echo `grep "Fullname=" "${SCRIPTDIR}/pltfrms/${1}.info" | awk -F'=' '{print $2}'`
} # end of getpackfullname



getpackinfo ()
{
  grep "System:${PLATFORM}=" "${SCRIPTDIR}/pltfrms/${1}.info" | awk -F'=' '{print $2}'
} # end of getpackinfo


  
getpacks ()
{
  #
  # Types: reqinst, optinst, allinst, reqdeinst, optdeinst, alldeinst.
  #
  if [ "x$1" = "xreqinst" ] ; then
    echo `grep "Reqpacks.inst=" "${PLATFORMDIR}/PACKS.info" | awk -F'=' '{print $2}'`
  elif [ "x$1" = "xoptinst" ] ; then
    echo `grep "Optpacks.inst=" "${PLATFORMDIR}/PACKS.info" | awk -F'=' '{print $2}'`
  elif [ "x$1" = "xallinst" ] ; then
    echo "`getpacks reqinst`:`getpacks optinst`"
  elif [ "x$1" = "xreqdeinst" ] ; then
    echo `grep "Reqpacks.deinst=" "${PLATFORMDIR}/PACKS.info" | awk -F'=' '{print $2}'`
  elif [ "x$1" = "xoptdeinst" ] ; then
    echo `grep "Optpacks.deinst=" "${PLATFORMDIR}/PACKS.info" | awk -F'=' '{print $2}'`
  elif [ "x$1" = "xalldeinst" ] ; then
    echo "`getpacks reqdeinst`:`getpacks optdeinst`"
  fi
} # end of getreqpacks



getscriptdir ()
{
  COMMANDLINE="${1}"
  CWD=`pwd`
  cd `dirname "${COMMANDLINE}"` 
  SCRIPTDIR=`pwd`
  cd "${CWD}"
} # end of getscriptdir



getyesno ()
{
  DEFAULT=`echo "${1}" | tr [A-Z] [a-z]`
  read A
  ANSWER=`echo "${A}" | tr [A-Z] [a-z]`
  if [ "x${ANSWER}" = "x" ] ; then
    ANSWER="${DEFAULT}"
  fi
  if [ "x${ANSWER}" != "xy" -a "x${ANSWER}" != "xn" ] ; then
    ANSWER="n"
  fi
} # end of getyesno



hr ()
{
echo "--------------------------------------------------------------------------------"
} # end of hr



mainmenu ()
{
  while true ; do
    clear
    echo ""
    echo "  Deinstall ${PRODUCT} on ${PLATFORMFULL} - Main Menu"
    hr
    echo ""
    echo "      1) Start deinstallation"
    echo "      2) Show package status"
    echo "      3) View deinstallation log"
    echo "      q) Quit"
    echo ""
    echo ""
    "${PRINTF}" "  Your choice? [1]: "
    read A
  
    case "${A}" in
      ""|"1")
        deinstallmenu
        mainmenu
        break
      ;;
      "2")
        showstatus
        : > "${TMPFILE}"
        mainmenu
        break
      ;;
      "3")
        viewlog
        mainmenu
        break
      ;;
      "q")
        clear
        break
      ;;
    esac
  done
} # end of mainmenu



setprintf ()
{
  PRINTF="printf"
  if [ ! -x "${PRINTF}" ] ; then
    if [ `echo "x\c"` = "x" ] ; then
      PRINTF="echoc"
    else
      PRINTF="echon"
    fi
  fi
} # end of setprintf



showstatus ()
{
  clear
  echo ""
  echo "  Deinstall ${PRODUCT} on ${PLATFORMFULL} - Show package status"
  hr
  echo ""
  echo ""
  PACKS=`getpacks alldeinst`
  echo "    Name	Status		Description"
  echo "    ========================================================================"
  for PACK in `echo "${PACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    PACKINFO=`getpackinfo "${PACK}"`
    STATUS=`"${FUNCS}" checkpack "${PACKINFO}"`
    echo "    ${PACK}	(${STATUS})	`getpackfullname "${PACK}"`"
  done
  entertocontinue
  return 0
} # end of showstatus



viewlog ()
{
  clear
  more -c "${LOGFILE}"
  echo ""
  entertocontinue
  return 0
} # end of viewlog



# MAIN BLOCK
#------------------------------------------------------------------------------
#

PRODUCT="GEAR Unix GUI DEMO"

USERID=`id | sed -e 's/uid=\([0-9][0-9]*\).*/\1/'`

if [ "${USERID}" != 0 ] ; then
  echo "You need root priveleges to deinstall GEAR."
  exit
fi

# Get the place of the installation script and set the CWD to it.
getscriptdir "${0}"
STARTDIR=`pwd`
cd "${SCRIPTDIR}"

setprintf
createtmp
detectplatform
"${FUNCS}" funcsinit || exit "$?"
PLATFORMFULL="`${FUNCS} osinfo -v`"
PLATFORM="`${FUNCS} osinfo`"
createlog
mainmenu
cleantmp

echo ""
echo "  ${PRODUCT} Post-deinstallation"
hr
echo ""

for i in `echo "${INITPACKS}" | sed -e "s,:, ,g"` ; do
  if [ -x "${PLATFORMDIR}/${i}.init" ] ; then
    OLD=`pwd`
    cd "${PLATFORMDIR}"
    ./"${i}.init" deinstall
    cd "${OLD}"
  fi
  if [ -x "${SCRIPTDIR}/pltfrms/${i}.init" ] ; then
    OLD=`pwd`
    cd "${SCRIPTDIR}/pltfrms"
    ./"${i}.init" deinstall
    cd "${OLD}"
  fi
done

echo " "
echo "  Deinstallationscript has finished - Press <enter> to continue"
read A
clear

# Return to the directory in which we called the script.
cd "${STARTDIR}"
