#!/bin/sh
#
#ident	"@(#)postpatch	1.12	05/11/09 SMI"
#
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

PATH="/usr/bin:/usr/sbin:${PATH}"
PKGCOND=/usr/bin/pkgcond

CheckZones()
{
	if [ "$ROOTDIR" = "/" -a -x /usr/bin/zonename ]; then
		ZONENAME=`/usr/bin/zonename`
		if [ ${ZONENAME} = "global" ]; then
			GLOBAL_ZONE=true
		else
			GLOBAL_ZONE=false
		fi
	else
		# Unable to determine zone
		GLOBAL_ZONE=true
	fi
}

LocalZones()
{
	return 0
}

ExecuteDefaultCmds()
{

	if [ -z "${ROOTDIR}" ]; then
		echo "\n$0 Failed: ROOTDIR is not set.\n" >&2
		exit 1
	fi

	DRVR_NAME=iscsi
	DRVR_PERM="-m '* 0600 root sys'"
	DRVR_NAME_UPDATE=sd
	DRVR_ALIAS_UPDATE="-i '\"scsiclass,00\"'"
	CHK_DRVR_ALIAS_UPDATE="scsiclass,00"
	DRIVER_ALIASES_FILE=${ROOTDIR}/etc/driver_aliases

	# Remove existing definition, if it exists. 
	rem_drv -b "${ROOTDIR}" ${DRVR_NAME} > /dev/null 2>&1

	if [ "$ROOTDIR" = "/" ] ; then
	  ADD_DRV="add_drv"
	  UPDATE_DRV="update_drv -a"
	else
	  ADD_DRV="add_drv -b ${ROOTDIR}"
	  UPDATE_DRV="update_drv -b ${ROOTDIR} -a"
	fi

	eval ${ADD_DRV} "${DRVR_PERM}" ${DRVR_NAME}
	if [ $? -ne 0 ]; then
		echo "\nCommand Failed:\n\t${ADD_DRV} ${DRVR_PERM} ${DRVR_NAME}\n" >&2
		exit 1
	fi

	grep "^${DRVR_NAME_UPDATE}[ 	]"\"*${CHK_DRVR_ALIAS_UPDATE}\"* $DRIVER_ALIASES_FILE  > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		eval ${UPDATE_DRV} "${DRVR_ALIAS_UPDATE}" ${DRVR_NAME_UPDATE}
		if [ $? -ne 0 ]; then
			echo "\nCommand Failed:" >&2
			echo "${UPDATE_DRV} "${DRVR_ALIAS_UPDATE}" ${DRVR_NAME_UPDATE}\n" >&2
			exit 1
		fi
	fi
}

ExecuteInProperEnvironment()
{

	if $PKGCOND is_whole_root_nonglobal_zone > /dev/null 2>&1 ; then
		# Execute non-global whole root zone commands.
		# Should be same action as the default action.
		return 0
	fi

	if $PKGCOND is_nonglobal_zone > /dev/null 2>&1 ; then
		# Execute non-global zone commands. Should be no action here
		return 0
	fi

	if $PKGCOND is_netinstall_image > /dev/null 2>&1 ; then
		# Execute commands applicable to patching the mini-root.
		# There are usually no actions to take here since your patching
		# the mini-root on an install server.
		return 0
	fi

	if $PKGCOND is_mounted_miniroot > /dev/null 2>&1 ; then
		# Execute commands specific to the mini-root
		return 0
	fi

	if $PKGCOND is_diskless_client > /dev/null 2>&1 ; then
		# Execute commands specific to diskless client
		return 0
	fi

	if $PKGCOND is_alternative_root > /dev/null 2>&1 ; then
		# Execute commands specific to an alternate root
		ExecuteDefaultCmds
		return 0
	fi

	if $PKGCOND is_global_zone > /dev/null 2>&1 ; then
		# In a global zone and system is mounted on /.
		# Execute all commands.
		ExecuteDefaultCmds
		return 0
	fi

	return 1
}

if [ -x $PKGCOND ] ; then
	ExecuteInProperEnvironment
else
	CheckZones

	if [ "${GLOBAL_ZONE}" = "true" ]; then
		ExecuteDefaultCmds
	else
		LocalZones
	fi
fi

exit 0
