#!/bin/ksh -p
#
# ident "@(#)utinstall.ksh	1.115 08/08/13 SMI"
#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

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

#
# Solaris 10 Trusted Extension guard
#
ORIGIN=`/usr/bin/dirname $0`
UTIL_LIB=${ORIGIN:-/opt/SUNWut/lib}/../lib/support_lib/util_lib
. $UTIL_LIB
FailExecInLocalZoneOnTx 
#
# Solaris 10 Trusted Extension guard 
#


trap "CleanupAndExit 1" HUP INT QUIT TERM

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

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

#
# function 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
#

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


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


   if [[ $G_MODE = "install" ]]; then
      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.
	!

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

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

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

# SERVICETAGS DELETE START
function InstallSvt {
  SVT_REL="1.0"
  SVT="Service_Tags_$SVT_REL"
  SVTPKG="SUNWutsvt"
  SVTRPM="SUNWutsvt-$SVT_REL-*.i386.rpm"

  if $G_MEDIA_DIR/utprodinfo -t installed $SVTPKG; then
        return 0;
  fi

  print "\nInstalling Service Tags $SVT_REL"
  case "$G_OS" in
  SunOS)
    print "\n+++ $SVTPKG"
    pkgadd -a $G_PRODUCT_DIR/.install/admin_default \
      -d $G_PRODUCT_DIR/$SVT/Solaris_10+/$G_ISA/Packages $SVTPKG
    ;;
  Linux)
    print "\n+++ $SVTRPM"
    rpm -i $G_PRODUCT_DIR/$SVT/$G_OS/Packages/$SVTRPM
    ;;
  esac
}
# SERVICETAGS DELETE END

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

function 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
# SERVICETAGS DELETE START
      InstallSvt
# SERVICETAGS DELETE END 
   else # {
      if [[ $G_MODE = "uninstall" ]] ; then # {
	 # Check if interface is configured
	 if [[ $CONFIGURED = "true" ]]; then
            print "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
		print "Unconfiguring Sun Ray Replication...\n"
		$UT_ETC_DIR/basedir/sbin/utreplica -u
            fi
            print "Unconfiguring Sun Ray Data Store...\n"
            $UT_ETC_DIR/basedir/sbin/utconfig -fu
	 fi
	 if [ "$G_OS" = "Linux" ]; then
	    # Determine GDM Install Path
	    GDM_PATH=`rpm -ql "gdm" | grep "Init/Default" `
	    if [ $? != 0 ]; then
        	print -u2 "Cannot determine GDM install directory"
		break;
	    fi
	    GDM_DIR=${GDM_PATH%%Init\/Default*}

	    for display in `ls "${GDM_DIR}PreSession" 2>/dev/null`; do
		if  ls -l ${GDM_DIR}PreSession/$display |  \
				grep SunRay >/dev/null 2>&1; then
	    		rm ${GDM_DIR}PreSession/$display
		fi
	    done
	    for display in `ls "${GDM_DIR}PostSession" 2>/dev/null`; do
		if  ls -l ${GDM_DIR}PostSession/$display |  \
				grep SunRay >/dev/null 2>&1; then
			rm ${GDM_DIR}PostSession/$display
		fi
	    done
	    for display in `ls "${GDM_DIR}PostLogin" 2>/dev/null`; do
		 if  ls -l ${GDM_DIR}PostLogin/$display |   \
				grep SunRay >/dev/null 2>&1; then
	    		rm ${GDM_DIR}PostLogin/$display
		fi
	    done
	    for display in `ls "${GDM_DIR}Init" 2>/dev/null`; do
		if ls -l ${GDM_DIR}Init/$display  |  \
			grep SunRay >/dev/null 2>&1; then
	    		rm ${GDM_DIR}Init/$display
		fi
	    done
      	 fi
      fi
      # }
      SendEventToModule Remove 
   fi
   # }

   PrintFinalMessage

   CleanupAndExit 0
}

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

# function main {

# 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: 4.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
# }
