#!/bin/ksh -p
#
# ident "@(#)utinstall.ksh	1.99 05/08/10 SMI"
#
# Copyright 1999-2002,2004-2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

trap "CleanupAndExit 1" HUP INT QUIT TERM

#
# Usage()
#
# Description:
#    Shows usage string
#
# Parameters:
#    (none)
#

Usage() {
  cat 1>&2 <<-!
	Usage: $G_PROGRAM_ID $PROGRAM_OPTS"

	 -a admin_file
	         specify an admin(4) file to be used by pkgadd(1m)
		 calls during install (Solaris only)

	 -d media_dir
	         specify a directory to install the software from

	 -j jre
	         specify a directory to find the Java Runtime Environment

	 -u      uninstall the software
	!

  CleanupAndExit 1
}

#
# CleanupAndExit()
#
# Description:
#    clean up procedure before exiting. Send Exit event in case of normal
#    termination (error code 0). Abort event otherwise (failure or 
#    interruption)
#
# Parameters:
#    $1 : exit code
#

CleanupAndExit() {
  trap "" HUP INT QUIT TERM

  #
  # remove preserve/upgrade temporary files if procedure terminated 
  # successfully and send termination event (Exit or Abort) to all modules to 
  # do their cleanup procedure
  #
  if [[ $1 = "0" ]]; then

     rm -rf ${G_UPGRADE_DIR}/preserve 1> /dev/null 2>&1

     if [[ $G_MODE = "install" ]]; then
        rm -rf ${G_UPGRADE_DIR} 1> /dev/null 2>&1
     fi
     SendEventToModule Exit
  else
     SendEventToModule Abort
  fi

  #
  # This function (CleanupAndExit) can be called from StartInstall (a function
  # which is in pipe with tee). The exit code cannot be seen by the main script
  # (utinstall) as the last task of the "pipeline" is tee. So, a temporary
  # file is created to communicate the error code to the main script 
  # (utinstall). Of course, this file is created if needed (just check if tee 
  # is running...)
  
  if ps -f | grep tee | grep ${G_PID} > /dev/null 2>&1 ; then
     echo $1 > $ERROR_FILE
  fi

  #
  # remove all temporary files created
  #
  rm -rf ${G_TMP_DIR} 1> /dev/null 2>&1

  exit $1
}


# Checks the version of the freetype rpm installed on the system
# Prints a warning if the version is lower than the required version
# Required version is 2.1.3-49

CheckFreetype() {

	ftype_ver=2.1.3
	ftype_bld=49
	ftype_lib="libfreetype.so.6"
	print_msg=0

	ftype=$(rpm -q --whatprovides $ftype_lib) 2>/dev/null
	fname=${ftype%%-*}
	ftyped=$(rpm -q ${fname}-devel) 2>/dev/null

	if [[ -z $ftype ]] || [[ -z $ftyped ]]; then
		print "\nWARNING:"
		print "The freetype rpm that provides $ftype_lib is required."
		print "Please install higher than ${ftype_ver}-${ftype_bld} version of the rpm."
		return
	fi

	ver=${ftype#${fname}-}
	v1=${ver%-*}
	bld=${ver#*-}
	verd=${ftyped#${fname}-devel-}
	v1d=${verd%-*}
	bldd=${verd#*-}
	CompareVersion $v1 ${ftype_ver}
	ret=$?
	if [[ $ret = 2 ]] || [[ $ret = 0 && $bld < ${ftype_bld} ]]; then 
		print_msg=1
	fi
	CompareVersion $v1d ${ftype_ver}
	ret=$?
	if [[ $ret = 2 ]] || [[ $ret = 0 && $bldd < ${ftype_bld} ]]; then 
		print_msg=1
	fi
	if [[ $print_msg = 1 ]]; then
		print "\nWARNING:"
		print "The following rpm versions or above are required : "
		print "\t${fname}-${ftype_ver}-${ftype_bld}"
		print "\t${fname}-devel-${ftype_ver}-${ftype_bld}"
		print "Please refer to the Installation Guide."
	fi
}

PrintFinalMessage() {
   #
   # Description:
   #    Just to print a message at the end of installation/uninstallation
   #
   # Parameters:
   #    (none)
   #


   if [[ $G_MODE = "install" ]]; then
      case "$G_OS" in
		Linux) CheckFreetype
		       ;;
      esac
      fmt <<-!

	Installation of $G_UT_PROD_NAME has completed.

	The system must be rebooted in order to complete this installation
	and before starting the $G_UT_PROD_NAME services.
	!

   elif [[ $G_MODE = "uninstall" ]]; then
      print "\nThe system must be rebooted in order to complete un-install."
   fi
}

#
# CheckDirectories()
#
# Description:
#    Check existence of install directories (support_lib, modules)
#
# Parameters:
#    (none)
#
# Globals used:
#    G_MEDIA_DIR

CheckDirectories() {

   # Check existence of support_lib dir. if it doesn't, libraries cannot be
   # sourced
   if [[ ! -d $G_MEDIA_DIR/support_lib ]]; then
      echo "$0: Error, cannot find support_lib directory"
      exit 1
   fi

   # Check existence of modules dir. if it doesn't, modules cannot be 
   # called.
   if [[ ! -d $G_MEDIA_DIR/iu_modules ]]; then
      echo "$0: Error, cannot find modules directory"
      exit 1
   fi

   return 0
}


#
# StartInstall()
#
# Description:
#    To kick off the install/uninstall procedure
#
# Parameters:
#    (none)
#

StartInstall() {

   #
   # Initialize all modules
   #
   SendEventToModule Init

   if PrintPostInitMessage && ! YesOrNo "\n\nContinue?" "Y"; then
      CleanupAndExit 1
   fi

   #
   # Start the install/unistall process
   #
   if [[ $G_MODE = "install" ]]; then
      SendEventToModule Preserve Remove Install Restore
   else

      if [[ $G_MODE = "uninstall" ]] ; then
	 # Check if interface is configured
	 if [[ $CONFIGURED = "true" ]]; then
            echo "Unconfiguring Sun Ray Interconnect...\n"
	    #Check if LAN is configured 
            if grep "^[ 	]*allowLANConnections" $UT_ETC_DIR/auth.props | grep true 1>/dev/null 2>&1; then 
               $UT_ETC_DIR/basedir/sbin/utadm -L off >/dev/null 2>&1 
            fi 
            # Unconfigure Sun Ray Interconnect
            $UT_ETC_DIR/basedir/sbin/utadm -r 
	 fi
         # Check if Configured
	 if [[ -f  $UTADMIN_CONF ]] ; then
            # Check if Replication is enabled
            if grep '^pu.._replica' $UT_ETC_DIR/srds/current/utdsd.conf >/dev/null 2>&1 ; then
		echo "Unconfiguring Sun Ray Replication...\n"
		$UT_ETC_DIR/basedir/sbin/utreplica -u
            fi
            echo "Unconfiguring Sun Ray Data Store...\n"
            $UT_ETC_DIR/basedir/sbin/utconfig -fu
	 fi
      fi

      SendEventToModule Remove 
   fi

   PrintFinalMessage

   CleanupAndExit 0
}

GetG_PRODUCT_DIR() {
  (
    cd $(dirname $1)
    print "$(pwd)/.."
  )
}

# main() {

PATH="/bin:/usr/bin:/usr/sbin"
#
# must include both '/bin' and '/usr/bin' (Linux/Solaris)

# global variables definition
#

export G_OS="$(uname -s)"

case "$(uname -m)" in
  sun4*)      export G_ISA="sparc";;
  i?86*|i86*) export G_ISA="i386";;
esac  

export G_OS_REL="$(uname -r)"

# location of the products
#
export G_PRODUCT_DIR="$(GetG_PRODUCT_DIR $0)"

# location of the support_lib and modules directories
export G_MEDIA_DIR="$G_PRODUCT_DIR/lib"

# Perform sanity checks on directories
CheckDirectories

#
# include libraries and definitions
#

. ${G_MEDIA_DIR}/support_lib/gl_defs
. ${G_MEDIA_DIR}/support_lib/iu_lib
. ${G_MEDIA_DIR}/support_lib/master_lib
. ${G_MEDIA_DIR}/support_lib/util_lib

#
# local variables definition
#
UT_ETC_DIR="/etc/opt/SUNWut"
UTADMIN_CONF="$UT_ETC_DIR/utadmin.conf"
CONFIGURED=""

typeset -r TMP_ADMIN_FILE="${G_TMP_DIR}/${G_PROGRAM_ID}.${G_PID}.admin_default"

# ERROR_FILE must be under G_TMP, not G_TMP_DIR.  The directory G_TMP_DIR
# contains the temporary working files and is deleted while the ERROR_FILE
# is still in use.
typeset -r ERROR_FILE="${G_TMP}/.${G_PROGRAM_ID}.${G_PID}.errcode"

typeset -r OPTSTR="a:d:j:ufv"
typeset -r PROGRAM_OPTS="[-a admin_file] [-d media_dir] [-j jre] [-u]"

G_ADMIN_FILE=""

while getopts $OPTSTR OPT; do
  case "$OPT" in
    a) G_ADMIN_FILE="$OPTARG";;
    d) G_PRODUCT_DIR="$OPTARG";;
    j) G_JRE="$OPTARG";;
    f) G_QUICK_INSTALL="yes";;
    u) G_MODE="uninstall";;
    v) G_DEBUG="yes";;
    *) Usage;;
  esac
done
shift $(($OPTIND - 1))

if (( $# != 0 )); then
  Usage
fi

if [[ -z "$G_ADMIN_FILE" ]]; then
  G_ADMIN_FILE=$G_PRODUCT_DIR/admin_default
  #
  # must be assigned after cmdline opts are parsed, G_PRODUCT_DIR change
else
  case "$G_OS" in
    Linux) Fatal "option '-a' can not be used on Linux";;
  esac
fi

if [[ ! -f $G_ADMIN_FILE ]]; then
   G_ADMIN_FILE="/opt/SUNWut/etc/admin_default"
fi

#
# sanity checks
#
CheckUidIsZero

CheckMediaDir

# change into root directory to avoid the problem of 
# being invoked in one of the SunRay directories.
#
cd /

case "$G_OS" in
SunOS)
  CheckAdminFile

  cp "$G_ADMIN_FILE" "$TMP_ADMIN_FILE"
  G_ADMIN_FILE="$TMP_ADMIN_FILE"
  ;;
esac

# if uninstalling the software, copy support_lib and modules directory
# in a temporary location. Otherwise, they will be removed with the rest of
# the software
#
if [[ $G_MODE = "uninstall" ]]; then
  CONFIGURED=$(/etc/opt/SUNWut/dhcp/utdhcpservice | grep configured | awk -F= '{print $2}')
  if [[ -f $UTADMIN_CONF ]] \
  || [[ $CONFIGURED = "true" ]] ; then
    print "\nWARNING: Sun Ray Server configuration detected.  Uninstalling"
    print "         the product will remove the existing configuration.\n"
  fi

  rm -rf ${G_TMP_DIR}/support_lib >/dev/null 2>&1
  rm -rf ${G_TMP_DIR}/iu_modules >/dev/null 2>&1
  rm -rf ${G_TMP_DIR}/utprodinfo >/dev/null 2>&1

  cp -pr ${G_MEDIA_DIR}/support_lib ${G_TMP_DIR}/support_lib >/dev/null 2>&1
  if [[ $? != 0 ]]; then
    Fatal "cannot copy support library in a temporary directory"
  fi

  cp -pr ${G_MEDIA_DIR}/iu_modules ${G_TMP_DIR}/iu_modules >/dev/null 2>&1
  if [[ $? != 0 ]]; then
    Fatal "cannot copy modules in a temporary directory"
  fi

  cp -pr ${G_MEDIA_DIR}/utprodinfo ${G_TMP_DIR}/utprodinfo >/dev/null 2>&1
  if [[ $? != 0 ]]; then
    Fatal "cannot copy utprodinfo in a temporary directory"
  fi

  G_MEDIA_DIR=${G_TMP_DIR}
fi

print "# $G_PROGRAM_ID   Version: 3.1     $(date)\n" |tee $G_LOGFILE

StartInstall 2>&1 | tee -a $G_LOGFILE

cat <<-!

	Please check for errors/warnings in

	    $G_LOGFILE

	+++ Done.
	!

# As StartInstall is in pipe with tee, we never get the exit code of it
# (we get the one from tee instead, which is always 0). The cleanup procedure,
# then, create a temporary file (ERROR_FILE) which contains the error code
# of StartInstall. 

if [[ -f $ERROR_FILE ]]; then
  errcode="$(cat $ERROR_FILE)"
  rm -f $ERROR_FILE
  exit $errcode
fi

exit 0
# }
