#! /bin/sh
#set -x 
#
# Arguments to installer:
#
#	-l enables the button
#	-L is the program to run
#	-B is the string to be put in the button
#

# Set and export a minimal path.

PATH=$PATH:/usr/bin:/usr/sbin
export PATH

# Check to make sure that the script is being run as root.

if [ `id | sed -e 's/[^(]*(//' -e 's/).*//'` != root ]; then
  echo " "
  echo "ERROR: You must be root to install software."
  echo " "
  exit 1
fi

pgmname=`basename $0`
thedate=`date +%Y-%m-%d_%T`
LOG=/usr/tmp/$pgmname"_log".$thedate

#
# Try to find workshop_install and use the absolute directory
# name to locate the packages.
#
# Algorithm:
#
#   1. If workshop_install was invoked with a leading / , assume
#   the given path is a full path name.
# 
#   2. If workshop_install is invoked starting with ./, use that
#   directory name in addition to the current working directory
#   to calculate the full path name.
#
#   3. Otherwise, search the path and use the first workshop_install
#   encountered.
#
#   4. If none of the above work, exit gracefully.
#
# Result should be EXEC_DIR containing the full path name of the directory
# which holds the workshop_install script.
#
PWD=`pwd`

FIRST=`echo $0 | awk -F/ '{ print $1 }' `

if [ -z "${FIRST}" ]; then
  # Either Leading slash or nothing specified
  if [ -z "$0" ]; then
    echo "Error: No command specified. Exiting..."
    exit 1
  else
    # Absolute path assumed
    EXEC_DIR=`dirname $0`
  fi
elif [ "${FIRST}" = "." ]; then
  # ./<pathname or executable>
  EXEC_DIR=${PWD}/`dirname $0`
  if [ ! -d ${EXEC_DIR} ]; then
    echo "Error: Cannot find executable directory. Exiting..."
    exit 1
  fi
else
  # <name>/<path> or <name>
  echo $0 | grep / > /dev/null 2>&1
  
  if [ $? -eq 0 ]; then
    # There is a slash in the pathname, assume it is relative
    EXEC_DIR=${PWD}/`dirname $0`
    
  else
    # No slash in the pathname, find it in the path
    PATH_DIRS=`echo $PATH | awk -F: '{ for ( i = 1; i <= NF; i++) print $i }'`
      if [ -z "${PATH_DIRS}" ]; then
	echo "Error: Cannot determine location of executable from $PATH, Exiting..."
	exit 1
      fi
      
      for d in ${PATH_DIRS}; do
	if [ -f $d/$0 ]; then
	  EXEC_DIR=$d
	  continue
	fi
      done
  fi
fi

if [ "${EXEC_DIR}" = "." ]; then
  EXEC_DIR=${PWD}
fi

#
# EXEC_DIR should now contain the directory containing the 
# workshop_install script. 
#

# Create a temporary directory that contains the CDROM top-level contents.
# This is required so as to allow the CD to be unmounted/ejected after
# this tool has completed, even though it may leave child processes running
# for license administration.  Fixes BugID: 1259857

cd $EXEC_DIR
tmpdirec=/tmp/`basename $0`-tmpdir.$$
mkdir $tmpdirec
cd $tmpdirec
for i in $EXEC_DIR/.[a-zA-Z0-9]* $EXEC_DIR/*; do
  ln -s $i .
done

# Reset PWD/EXEC_DIR as this mockup directory.

orig_dir=$EXEC_DIR
PWD=`pwd`
EXEC_DIR=$PWD

# Check to make sure that the OS is valid.

case `uname -r` in
  4.*) os_valid=0;;
  *)   os_valid=1;;
esac

if [ $os_valid = 0 ]; then
  echo "PLATFORM ERROR: This installation tool must be run on a SunOS 5.x"
  echo "platform.  You are attempting to install onto a SunOS 4.1.x platform."
  echo "If you wish to install on this SunOS 4.1.x platform, please locate"
  echo "the SunOS 4.1.x media and invoke its installation tool.  Otherwise,"
  echo "please invoke this installation tool on a SunOS 5.x platform.  Exiting..."
  cd /
  rm -rf $tmpdirec
  exit 1
fi

# Check to make sure that we can open an X display.

$EXEC_DIR/bin/test_display >/dev/null 2>&1
status=$?

if [ $status != 0 ]; then
  echo ""
  echo "DISPLAY ERROR: Could not open an X Window display.  Please check the"
  echo "setting of your DISPLAY environment variable, and if need be,"
  echo "execute an \"xhost\" command on this display to grant access."
  echo "Proper execution of the \"xhost\" command is documented in your"
  echo "install guide."
  echo ""
  echo "If you have become the root user on this display by means of an \"su\""
  echo "command, you will likely have to issue an \"xhost\" command as the"
  echo "owner of the display, not as root.  See the install guide for more"
  echo "information on setting \"xhost\" access prior to becoming root."
  echo ""
  cd /
  rm -rf $tmpdirec
  exit 1
fi

#
# Set NLSPATH so that the installer will pick up the proper
# message file
#
NLSPATH=${EXEC_DIR}/locale/%L/LC_MESSAGES/%N:${NLSPATH}
export NLSPATH

XFILESEARCHPATH=${EXEC_DIR}/locale/%L/app-defaults/%N:${XFILESEARCHPATH}
export XFILESEARCHPATH

#
# To solve the problem where the "Install Licenses" button
# is not properly translated, don't try to set it to a non-default
# value when not in the "C" locale.  This will cause installer
# to go to the message file for the value, in which we will have
# the translation for "Install Licenses".  Only do this if the
# message file for this locale is properly located on the CD.
#
LIC_LABEL="Install Licenses"
LIC_LABEL_OPT=-B
if [ "${LANG}" != C -a "${LANG}" != "en_US" ]; then
  if [ -f ${EXEC_DIR}/locale/${LANG}/LC_MESSAGES/admintool.msg ]; then
    LIC_LABEL=""
    LIC_LABEL_OPT=""
  fi
fi


# 
# The online help files are shipped on the CD in the bin directory.
# Set the online help variable to point only at these files as
# the default help contains help for admintool and other functionality
# that is not available from installer.
#
ADMINHELPHOME=${EXEC_DIR}/bin/locale; export ADMINHELPHOME

echo "Installation output and errors are being directed to "
echo "the file ${LOG}."

DATE=`date`

echo "" >> ${LOG}
echo "This is the log file from the $0 command." >> ${LOG}
echo "DATE=${DATE}" >> ${LOG}
echo "" >> ${LOG}
echo "Any output or errors from the invocation of the installation tool" >> ${LOG}
echo "will be captured in this file" >>${LOG}
echo "" | /usr/bin/tee -a  ${LOG}

#
# Because the Sun WorkShop tools rely upon Motif being installed,
# check for the presence of the required libraries here. Warn
# the user that they do not have them installed if that is the 
# case. 
#
/usr/bin/ldd ${EXEC_DIR}/bin/installer | grep libXm. | grep -i "not found" > /dev/null

if [ $? -eq 0 ]; then
    # 
    # library not found, tell the user
    #
    cat <<EOMSG  | /usr/bin/tee -a ${LOG} 

ERROR: 

The Motif runtime library (libXm.so) cannot be found.  If it is
installed on this machine, make sure your LD_LIBRARY_PATH is set to
properly access the library, see ld(1) for more information about how
to set your LD_LIBRARY_PATH variable.  If the library is not installed
on this machine, you must use the command-line installation tools.

To install license software, product software and documentation: 

  ${EXEC_DIR}/bin/clustadd

If this is going to be a license server, you must install the "License
Manager Software and Utilities".  After you have installed these, the
command-line license installation tool will be:

  /etc/opt/licenses/lit_tty

NOTE: 

The graphical user interfaces (GUIs) for the products you are
installing also require the Motif runtime libraries to be installed
and accessible.  If you are going to be running these products on
this machine, you must install the Motif runtime libraries. 

EOMSG

cd /
rm -rf $tmpdirec
exit 1;

fi

#
# End checking for libXm
#

# SW
#
# As a workaround to the installer not being able to change the
# installation directory, ask the user where they would like
# to put the software.  Take the response, create it if it
# doesn't exist, and put it in an admin file in /tmp as the
# basedir value.
#
ADM_FILE=/tmp/$pgmname"_admin".$$
CONT=no
CHG_LOC=no

CONT=no
CHG_LOC=no

/usr/ucb/echo "The software will be installed by default in /opt." | /usr/bin/tee -a ${LOG}

while [ "${CONT}" = "no" ]; do
  /usr/ucb/echo -n "Okay to use the default, /opt? <y|n>: " | /usr/bin/tee -a ${LOG}
  read response
  echo "${response}" >> ${LOG}
  
  if [ "${response}" = "y" -o \
         "${response}" = "Y" ]; then
         CHG_LOC=no
	 CONT=yes
  elif [ "${response}" = "n" -o \
         "${response}" = "N" ]; then
         CHG_LOC=yes
	 CONT=yes
  elif [ -z "${response}" ]; then
         echo "Please enter 'y' or 'n'" | /usr/bin/tee -a ${LOG}
  fi
done


if [ ${CHG_LOC} = "yes" ]; then
  #
  # Get the new location and create it if needed
  #
  CONT=no
  while [ ${CONT} = "no" ]; do
    if [ ${CHG_LOC} = "yes" ]; then
      /usr/ucb/echo -n "Enter the name of the new directory: " | /usr/bin/tee -a ${LOG}
      read response
      echo "${response}" >> ${LOG}
      if [ -z "${response}" ]; then
	/usr/ucb/echo "Please enter a directory name." | /usr/bin/tee -a ${LOG}
      elif [ -d ${response} ]; then
	NEW_DIR=${response}
	CONT=yes
	echo "Using ${NEW_DIR} as the installation directory" | /usr/bin/tee -a ${LOG}
	echo "" | /usr/bin/tee -a ${LOG}
      elif [ ! -d ${response} ]; then
	echo "The directory ${response} does not exist. " | /usr/bin/tee -a ${LOG}
	/usr/ucb/echo -n "Would you like it to be created? <y|n|CR to change value>: " | /usr/bin/tee -a ${LOG}
	read newdir
	echo "${newdir}" >> ${LOG}
	if [ "${newdir}" = "n" -o "${newdir}" = "N" ]; then
	  /usr/ucb/echo "Error: Cannot install into a nonexistent directory. Exiting." | /usr/bin/tee -a ${LOG}
          cd /
          rm -rf $tmpdirec
	  exit 1;
	elif [ "${newdir}" = "y" -o "${newdir}" = "Y" ]; then
	  mkdir -p ${response}
	  if [ ! -d ${response} ]; then
 	    /usr/ucb/echo "Error: Cannot create ${response}. " | /usr/bin/tee -a ${LOG}
	    /usr/ucb/echo "Exiting. " | /usr/bin/tee -a ${LOG}
            cd /
            rm -rf $tmpdirec
	    exit 1
	  fi
	  CONT=yes
	  NEW_DIR=${response}
	fi
      fi
    fi
  done
  
fi

#
# In order to be able to successfully install the packages without
# user intervention, a directory containing the response_files
# needs to be created.  It will created based upon the list of
# packages in the distribution directory as well as the list of
# packages already installed on the system.  If pkgadd is given
# a response file for PKG, and it is installing PKG.1, it will
# fail. 

#
RESP_DIR=/tmp/SSWS_response_files.$$

if [ -d ${RESP_DIR} ]; then
  rm -rf ${RESP_DIR}
fi
mkdir ${RESP_DIR}

#
# If the response file directory cannot be created for some reason,
# then default to an interactive installation
#
if [ -d ${RESP_DIR} ]; then
  NON_INTERACTIVE=true
fi

if [ "$NON_INTERACTIVE" = "true" ]; then
  INTER="-N -r ${RESP_DIR}"
  
  echo "Checking distribution directory..." | /usr/bin/tee -a ${LOG}
  echo "" | /usr/bin/tee -a ${LOG}

  #
  # First pass creates a response_file for each package on the
  # distribution media
  #
  cd $EXEC_DIR/packages

  find * -type f -name "pkginfo" -exec dirname  {} \; > /usr/tmp/$pk1.$$
  for d in `cat /usr/tmp/$pk1.$$`  
  do 
      touch ${RESP_DIR}/$d
  done
  rm -f /usr/tmp/$pk1.$$
  cd $PWD

  #
  # Packages which require special content in the 
  # response files: 
  #
  SPECIAL_PKGS="SPROvisu SPROesrt SPROabcc SPROabcpl SPROabftn SPROabins SPROabov SPROabtw SPROabws"

  for p in ${SPECIAL_PKGS}; do
    if [ -d ${EXEC_DIR}/packages/$p ]; then
      rm ${RESP_DIR}/$p
      echo "===============" >>${LOG}
      echo "Pre-processing output for package $p appears below and may be ignored." >>${LOG}
      pkgask -r ${RESP_DIR}/$p -d ${EXEC_DIR}/packages $p >> ${LOG} 2>&1
      if [ "$NEW_DIR" != "" ];
      then
       	  cat ${RESP_DIR}/$p | sed -e "s;COLL_PARENTDIR=/opt;COLL_PARENTDIR=${NEW_DIR};" -e "s;AB2INSTALLDIR=/opt;AB2INSTALLDIR=${NEW_DIR};" -e "s;AB2DATADIR=/opt;AB2DATADIR=${NEW_DIR};" > ${RESP_DIR}/$p.new
	  mv ${RESP_DIR}/$p.new ${RESP_DIR}/$p
      fi
      echo "End of pre-processing output for package $p" >>${LOG}
      echo "===============" >>${LOG}
    fi
  done
  
  echo "Checking for previously installed packages..." | /usr/bin/tee -a ${LOG}
  echo "" | /usr/bin/tee -a ${LOG}
  
  #
  # Second pass creates a pkgname.# file for each potential
  # package to be created by pkgadd.  For each package installed
  # if there is already a response file, create a new one with the
  # suffix incremented.
  #

  pkginfo | awk '{ print $2 }' >$tmpdirec/pkgs
  
  cd $EXEC_DIR/packages
  for d in */pkginfo; do
    PREFIX=`dirname $d`
    pkg_vers=`cat $tmpdirec/pkgs | grep $PREFIX`

    for p in $pkg_vers; do
      CURR_SFX=`echo $p | awk -F. '{ print $2 }'`
	
      if [ -n "$CURR_SFX" ]; then
        MAX_SFX=`expr $CURR_SFX + 1`
      else
        # The suffix used by pkgadd starts with "2", not "1"
        MAX_SFX=2
      fi

      CURR_SFX=2

      while
        :
      do
        if [ "$PREFIX" = "SPROvisu" ]; then
          cp $RESP_DIR/SPROvisu $RESP_DIR/SPROvisu.$CURR_SFX
        elif [ "$PREFIX" = "SPROesrt" ]; then
          cp $RESP_DIR/SPROesrt $RESP_DIR/SPROesrt.$CURR_SFX
        elif [ "$PREFIX" = "SPROabcc" ]; then
          cp $RESP_DIR/SPROabcc $RESP_DIR/SPROabcc.$CURR_SFX
        elif [ "$PREFIX" = "SPROabcpl" ]; then
          cp $RESP_DIR/SPROabcpl $RESP_DIR/SPROabcpl.$CURR_SFX
        elif [ "$PREFIX" = "SPROabftn" ]; then
          cp $RESP_DIR/SPROabftn $RESP_DIR/SPROabftn.$CURR_SFX
        elif [ "$PREFIX" = "SPROabins" ]; then
          cp $RESP_DIR/SPROabins $RESP_DIR/SPROabins.$CURR_SFX
        elif [ "$PREFIX" = "SPROabov" ]; then
          cp $RESP_DIR/SPROabov $RESP_DIR/SPROabov.$CURR_SFX
        elif [ "$PREFIX" = "SPROabtw" ]; then
          cp $RESP_DIR/SPROabtw $RESP_DIR/SPROabtw.$CURR_SFX
        elif [ "$PREFIX" = "SPROabws" ]; then
          cp $RESP_DIR/SPROabws $RESP_DIR/SPROabws.$CURR_SFX
        else 
          touch $RESP_DIR/$PREFIX.$CURR_SFX
        fi

        if [ $CURR_SFX = $MAX_SFX ]; then
          break
        else
          CURR_SFX=`expr $CURR_SFX + 1`
        fi
      done
    done
  done
  cd $PWD
else
  #
  # Cannot create response files directory, perform an interactive
  # installation 
  #
  INTER=

  echo "Warning: Cannot create the directory required for non-interactive" | /usr/bin/tee -a ${LOG} 
  echo "installation. To fix this, make sure you can write to /tmp and interactive" | /usr/bin/tee -a ${LOG}
  echo "installation will be enabled the next time you invoke $0." | /usr/bin/tee -a ${LOG}
  echo "" | /usr/bin/tee -a ${LOG}
  
fi

#
# Regardless, create an adminfile, and set ADM_FILE for the
# installer command later on
#
if [ "$NON_INTERACTIVE" = "true" ]; then
  cp $EXEC_DIR/packages/.admin_file-noninter $ADM_FILE
else
  cp $EXEC_DIR/packages/.admin_file-inter $ADM_FILE
fi

chmod +w $ADM_FILE

if [ -n "${NEW_DIR}" ]; then
  echo "basedir=${NEW_DIR}" >> ${ADM_FILE}
else
  echo "basedir=/opt" >> ${ADM_FILE}
fi
    
echo "Invoking installer" | /usr/bin/tee -a ${LOG}
echo "" | /usr/bin/tee -a ${LOG}

# 
# If on the Intel platform, set the LD_LIBRARY_PATH 
# value to include the bin directory from the top level of the CD.
#

if [ `/usr/bin/uname -p` = "i386" -a ! -f /usr/lib/libdevinfo.so.1 ]; then
  LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${EXEC_DIR}/bin
  export LD_LIBRARY_PATH
fi
  
#
# Invoke the installer and redirect the output to various places
# 
# - All of it will go to the log file
# 
# - Lines with "error", "warning" or "fatal" and "pkgadd" will go to 
#   stdout as
#   well as the log file (case insensitive). To add another keyword
#   to this list, add "|<keyword>" to the egrep lines below. Make
#   sure to add them in both places. The two lines below are not
#   combined into one because the "Install Licenses" argument
#   could not be protected as a quoted string with the extra
#   level of indirection. 
#
#   In order to get multi-line errors,  start putting the lines
#   to stdout from when there is an error encountered until the
#   package messages are complete (indicated by "^Installation of"
#   message)
#
# There is a special case below.  The output from the pkgadd of the
# SUNWdthep command is supressed. It is only sent to the log file. 
# There will be warnings which can be ignored, so rather than displaying
# them and having to explain them, it is best all-around to only send
# them to the log file. 
#
echo "Invoking ${EXEC_DIR}/bin/installer -d ${EXEC_DIR}/packages ${INTER} -a ${ADM_FILE} -l -L ${EXEC_DIR}/licensing/lit ${LIC_LABEL_OPT} \"${LIC_LABEL}\"" >> ${LOG}  

${EXEC_DIR}/bin/installer -d ${EXEC_DIR}/packages ${INTER} -a ${ADM_FILE} -l -L ${EXEC_DIR}/licensing/lit ${LIC_LABEL_OPT} "${LIC_LABEL}" 2>&1 | \
  /bin/sh -c "while read line; do \
       if [ \"\$line\" = \"Separable help for CDE\" ]; then \
         SUNWDTHEP=TRUE; \
       fi; \
       if [ \"\$line\" = \"Installation of <SUNWdthep> was successful\" ]; then \
         SUNWDTHEP=FALSE; \
       fi; \
       OUT=\`echo \$line | egrep -i 'error|fatal|warning|pkgadd|cpio|failed'\`; \
       if [ ! -z \"\${OUT}\" -o \"\${PRINT_IT}\" = \"YES\" ]; then \
         PRINT_IT=YES; \
         if [ \"\$SUNWDTHEP\" != \"TRUE\" ]; then \
           echo \$line; \
         fi; \
         ENDCHECK=\`echo \$line | grep '^Installation of' \`; \
         if [ ! -z \"\${ENDCHECK}\" ]; then \
             PRINT_IT=NO; \
         fi; \
       fi; \
       echo \"\$line\" >> ${LOG}; \
     done"

# Generate an uninstall script based on the actions of this invocation.

UNINSTALL_SCRIPT=/usr/tmp/workshop_uninstall-"$thedate".sh
UNINSTALL_ADM_FILE=/usr/tmp/workshop_uninstall-"$thedate".admin

cp $ADM_FILE $UNINSTALL_ADM_FILE
rm -rf $ADM_FILE $RESP_DIR

echo "#!/bin/sh" >$UNINSTALL_SCRIPT
echo "" >>$UNINSTALL_SCRIPT
echo "# This script was automatically created by $pgmname on $thedate." >>$UNINSTALL_SCRIPT
echo "# When invoked, this script will remove all packages installed by" >>$UNINSTALL_SCRIPT
echo "# $pgmname on $thedate.  The installation log associated with" >>$UNINSTALL_SCRIPT
echo "# this script is maintained in the $LOG file." >>$UNINSTALL_SCRIPT
echo "" >>$UNINSTALL_SCRIPT
echo 'PATH=$PATH:/usr/sbin:/usr/bin' >>$UNINSTALL_SCRIPT
echo "export PATH" >>$UNINSTALL_SCRIPT
echo "" >>$UNINSTALL_SCRIPT
echo 'echo ""' >>$UNINSTALL_SCRIPT
echo 'echo "         Sun WorkShop Uninstaller"' >>$UNINSTALL_SCRIPT
echo 'echo ""' >>$UNINSTALL_SCRIPT
echo "echo Removing all packages installed by $pgmname on $thedate ..." >>$UNINSTALL_SCRIPT
echo "" >>$UNINSTALL_SCRIPT

tmpfile=$tmpdirec/$pgmname.pkglist
pkginst_list=`grep '^Installation of <' $LOG | grep '> was successful.$' | sed s:'^Installation of <':: | sed s:'> was successful.$'::`

touch $tmpfile

for i in $pkginst_list; do
  echo $i >>$tmpfile
done

pkginst_reverse_order=`cat -n $tmpfile | sort -r | awk '{ print $2 }'`

for i in $pkginst_reverse_order; do
  echo "pkginfo $i > /dev/null 2>&1" >>$UNINSTALL_SCRIPT
  echo "if [ \$? -eq 0 ]; then" >>$UNINSTALL_SCRIPT
  echo "pkgrm -n -a $UNINSTALL_ADM_FILE $i" >>$UNINSTALL_SCRIPT
  echo "fi" >> $UNINSTALL_SCRIPT
done

echo "" >>$UNINSTALL_SCRIPT
echo 'echo ""' >>$UNINSTALL_SCRIPT
echo "echo Uninstall completed." >>$UNINSTALL_SCRIPT
echo "" >>$UNINSTALL_SCRIPT
echo "exit 0" >>$UNINSTALL_SCRIPT

chmod a+x $UNINSTALL_SCRIPT

# Point users to the install_required_patches tool for further installation
# steps.

echo "Installation has completed.  Some of the products in this release require" | /usr/bin/tee -a ${LOG}
echo "patches to be installed.  Please look in the Patch directory and" | /usr/bin/tee -a ${LOG}
echo "review the specific README files of the supplied patches to see if" | /usr/bin/tee -a ${LOG}
echo "they apply to your product.  If you wish to install any of the" | /usr/bin/tee -a ${LOG}
echo "supplied patches, you may do so by running the" | /usr/bin/tee -a ${LOG}
echo "install_required_patches tool."  | /usr/bin/tee -a ${LOG}

# Remove the mockup temporary directory.

cd /
rm -rf $tmpdirec
