#!/bin/sh
#-------------------------------------------------------------------------------
#
#  Scriptname: install                         Platform: all
#      Author: Jeffry Sleddens            Creation date: 30/06/1999
#
# Description: Toplevel install 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)       Jeffry Sleddens          30/06/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.
# NUMPACKS                      Contains number of packages.
# 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.
# deinstallpacks                Function that finally removes 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.
# getpackdescription            Returns the description of the package.
# 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.
# installmenu                   Function that displays the deinstallmenu.
# installopt                    Function that installs optional packages.
# installpacks                  Function that finally installs packages.
# installreq                    Function that installs required packages.
# 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_install.log"
  else  
    LOGFILE="/gear_install.log"
  fi
  if [ -f "${LOGFILE}" ] ; then
    mv "${LOGFILE}" "${LOGFILE}.old"
  fi
  echo "" > "${LOGFILE}"
  echo "  Install ${PRODUCT} on ${PLATFORMFULL} - Installation 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_install.tmp"
  else  
    TMPDIR="/"
    TMPFILE="/gear_install.tmp"
  fi
  : > "${TMPFILE}"
  export TMPDIR TMPFILE
} # end of createtmp



deinstallpacks ()
{
  DPACKS="$*"
  clear
  echo ""
  echo "  Install ${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"
    fi
    echo ""
  done
  entertocontinue
} # end of deinstallpacks



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} installation 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



getpackdescription ()
{
  echo `grep "DS=" "${SCRIPTDIR}/pltfrms/${1}.info" | sed -e 's/^DS=/  /g'`
} # end of getpackdescription



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 ()
{
  #/* variable width HR */ Non Solaris-compatible
  #
  #echo `stty size`" $HR" | awk '{ if ( length($3) == $2 ) print $3
  #                                else {$3=""; while (length($3)<$2) $3=$3"-"; }; print $3}'
  #
  #
  echo "--------------------------------------------------------------------------------"
} # end of hr



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

     case "${A}" in
      "1")
        installreq
        installmenu
        break
      ;;
      "2")
        installopt
        installmenu
        break
      ;;
      "q"|"r")
        return 0
      ;;
      default)
        installmenu
        break
    esac
  done
} # end of installmenu



installopt ()
{
  PACKS=`getpacks optinst`
  NUMPACKS=`echo "${PACKS}" | awk -F':' '{print NF}'`
  clear
  echo ""
  echo "  Install ${PRODUCT} on ${PLATFORMFULL} - Installation of optional packages"
  hr
  echo ""

  if [ "x${PACKS}" = "x" ] ; then
    echo "  No optional packages were found for your platform."
    echo ""
    entertocontinue
    return 0
  fi    

  echo "  The following packages are optional:"
  echo ""
  for PACK in `echo "${PACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    echo "    `getpackfullname "${PACK}"`"
  done
  echo ""
  echo ""
  if [ "${NUMPACKS}" -gt "1" ] ; then
    "${PRINTF}" "  Do you want to install any of these package? (y/n) [y]: "
    getyesno y
    if [ "x${ANSWER}" = "xn" ] ; then
      return 0
    fi
    echo ""
  fi
  OPTIONS="${PACKS}"
  PACKS=""
  for PACK in `echo "${OPTIONS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    PACKFULL=`getpackfullname "${PACK}"`
    "${PRINTF}" "  Do you want to install the ${PACKFULL}? (y/n) [y]: "
    getyesno y
    if [ "x${ANSWER}" = "xy" ] ; then
      PACKS="${PACKS}${PACK}:"
    fi
  done

  INSTALLED=""
  if [ "x${PACKS}" != "x" ] ; then 
    for PACK in `echo "${PACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
      PACKINFO=`getpackinfo "${PACK}"`
      echo " "
      echo "  Checking presence of currently installed GEAR package(s)."
      if [ "x`"${FUNCS}" checkpack "${PACKINFO}"`" = "xinstalled" ] ; then
        INSTALLED="${INSTALLED}${PACK}:"
      fi
    done
    if [ "x${INSTALLED}" != "x" ] ; then
      echo ""
      echo ""
      echo "  Older versions of the selected packages have been found on your system."
      echo "  These older packages need to be removed first before you can continue."
      echo "" 
      "${PRINTF}" "  Do you want to continue? (y/n) [y]: "
      getyesno y
      if [ "x${ANSWER}" = "xn" ] ; then
        return 0
      fi 
      deinstallpacks "${INSTALLED}"
    fi 
    installpacks "${PACKS}"
  fi
 : > "${TMPFILE}"
 return 0
} # end of installopt



installpacks ()
{
  IPACKS="$*"
  clear
  echo ""
  echo "  Install ${PRODUCT} on ${PLATFORMFULL} - Installation progress"
  hr
  echo ""
  for PACK in `echo "${IPACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    PACKFULL=`getpackfullname "${PACK}"`
    "${PRINTF}" "  Installing ${PACKFULL} ... "
    PACKINFO=`getpackinfo "${PACK}"`
    "${FUNCS}" installpack "${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 installpacks



installreq ()
{
  PACKS=`getpacks reqinst`
  clear
  echo ""
  echo "  Install ${PRODUCT} on ${PLATFORMFULL} - Installation of required packages"
  hr
  echo ""
  echo "  These packages are part of the main program and are required:"
  echo ""
  for PACK in `echo "${PACKS}" | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    echo "    `getpackfullname "${PACK}"`"
  done
  echo ""
  echo ""
  "${PRINTF}" "  Do you want to install the required packages? (y/n) [y]: "
  getyesno y
  if [ "x${ANSWER}" = "xn" ] ; then
    return 0
  fi

  INSTALLED=""
  for PACK in `getpacks reqdeinst | awk -F':' '{for (i=1;i<=NF;i++) print $i}'` ; do
    PACKINFO=`getpackinfo "${PACK}"`
    echo " "
    echo "  Checking presence of currently installed GEAR package(s)."
    if [ "x`"${FUNCS}" checkpack "${PACKINFO}"`" = "xinstalled" ] ; then
      INSTALLED="${INSTALLED}${PACK}:"
    fi
  done
  if [ "x${INSTALLED}" != "x" ] ; then
    echo ""
    echo ""
    echo "  Older versions of the required packages have been found on your system."
    echo "  These older packages need to be removed first before you can continue."
    echo "" 
    "${PRINTF}" "  Do you want to continue? (y/n) [y]: "
    getyesno y
    if [ "x${ANSWER}" = "xn" ] ; then
      return 0
    fi 
    deinstallpacks "${INSTALLED}"
  fi 
  installpacks "${PACKS}"
  : > "${TMPFILE}"
  return 0
} # end of installreq



mainmenu ()
{
  while true ; do
    clear
    echo ""
    echo "  Install ${PRODUCT} on ${PLATFORMFULL} - Main Menu"
    hr
    echo ""
    echo "      1) Start installation"
    echo "      2) Show package status"
    echo "      3) View installation log"
    echo "      q) Quit"
    echo ""
    echo ""
    "${PRINTF}" "  Your choice? [1]: "
    read A

    case "${A}" in
      ""|"1")
        installmenu
        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 [ "x`echo "x\c"`" = "xx" ] ; then
      PRINTF="echoc"
    else
      PRINTF="echon"
    fi
  fi
  export PRINTF
} # end of setprintf



showstatus ()
{
  clear
  echo ""
  echo "  Install ${PRODUCT} on ${PLATFORMFULL} - Show package status"
  hr
  echo ""
  echo ""
  PACKS=`getpacks allinst`
  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



showlicense ()
{
  if [ -f "${LICENSEFILE}" ] ; then
    clear
    more -c "${LICENSEFILE}"
    echo ""
    echo ""
    ANSWER=""
    while [ -z "${ANSWER}" ] ; do
      "${PRINTF}" "Do you accept the terms and conditions of this license agreement? (yes/no) "
      read ANSWER
      UCANSWER=`echo "${ANSWER}" | tr '[a-z]' '[A-Z]'`
      case "${UCANSWER}" in
      "YES"|"Y")
        ;;
      "NO"|"N")
        echo ""
        echo "License not accepted ... Aborting installation"
        echo ""
        exit 1
        ;;
      *)
        ANSWER=""
        ;;
      esac
    done
    clear
  fi
} # end of showlicense



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

PRODUCT="GEAR Unix GUI DEMO"

LICENSEFILE="license.txt"

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

if [ "${USERID}" -ne 0 ] ; then
  echo "You need root priveleges to install 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`"
showlicense
createlog
mainmenu
cleantmp

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

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

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

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