# This script creates the backout package for a patch package
#
# directory format options.
#
# @(#) postinstall 1.13 01/01/12 SMI
#
# Copyright (c) 1995 by Sun Microsystems, Inc.
# All rights reserved
#

# Description:
#       Set the TYPE parameter for the remote file
#
# Parameters:
#       none
#
# Globals set:
#	TYPE

set_TYPE_parameter () {
	if [ ${PATCH_UNDO_ARCHIVE:?????} = "/dev" ]; then
		# handle device specific stuff
		TYPE="removable"
	else
		TYPE="filesystem"
	fi
}

#
# Description:
#       Build the remote file that points to the backout data
#
# Parameters:
#       $1:	the un/compressed undo archive
#
# Globals set:
#	UNDO, STATE

build_remote_file () {
	remote_path=$PKGSAV/$SUNW_PATCHID/remote
	set_TYPE_parameter
	STATE="active"

	if [ $1 = "undo" ]; then
		UNDO="undo"
	else
		UNDO="undo.Z"
	fi

	cat > $remote_path << EOF
# Backout data stored remotely
TYPE=$TYPE
FIND_AT=$ARCHIVE_DIR/$UNDO
STATE=$STATE
EOF
}

PATH=/usr/sadm/bin:$PATH

if [ "$PKG_INSTALL_ROOT" = "/" ]; then
	PKG_INSTALL_ROOT=""
fi

if [ -n "$PATCH_BUILD_DIR" -a -d "$PATCH_BUILD_DIR" ]; then
	BUILD_DIR="$PATCH_BUILD_DIR/$SUNW_PATCHID.$PKGINST"
else
	BUILD_DIR="$PKG_INSTALL_ROOT/var/tmp/$SUNW_PATCHID.$PKGINST"
fi

if [ ! -n "$PATCH_UNDO_ARCHIVE" ]; then
	PATCH_UNDO_ARCHIVE="none"
fi

FILE_DIR=$BUILD_DIR/files
RELOC_DIR=$FILE_DIR/reloc
ROOT_DIR=$FILE_DIR/root
BO_Deletes=$FILE_DIR/deletes
THIS_DIR=`dirname $0`
PROTO_FILE=$BUILD_DIR/prototype
TEMP_REMOTE=$PKGSAV/$SUNW_PATCHID/temp

if [ "$PATCH_PROGRESSIVE" = "true" ]; then
        # remove the scripts that are left behind
        install_scripts=`dirname $0`
        rm $install_scripts/checkinstall $install_scripts/patch_checkinstall $install_scripts/patch_postinstall

	# If this is being used in an old-style patch, insert
	# the old-style script commands here.

	#XXXOld_CommandsXXX#

	exit 0
fi

#
# At this point we either have a deletes file or we don't. If we do,
# we create a prototype entry.
#
if [ -f $BO_Deletes ]; then
	echo "i deletes=$BO_Deletes" >> $BUILD_DIR/prototype
fi

#
# Now delete everything in the deletes list after transferring
# the file to the backout package and the entry to the prototype
# file. Remember that the pkgmap will get the CLIENT_BASEDIR path
# but we have to actually get at it using the BASEDIR path. Also
# remember that removef will import our PKG_INSTALL_ROOT
#
Our_Deletes=$THIS_DIR/deletes
if [ -f $Our_Deletes ]; then
	cd $BASEDIR

	cat $Our_Deletes | while read path; do
		Reg_File=0

		if valpath -l $path; then
			Client_Path="$CLIENT_BASEDIR/$path"
			Build_Path="$RELOC_DIR/$path"
			Proto_Path=$BASEDIR/$path
		else	# It's an absolute path
			Client_Path=$path
			Build_Path="$ROOT_DIR$path"
			Proto_Path=$PKG_INSTALL_ROOT$path
		fi

		# If BASEDIR/CLIENTBASEDIR = "/", then the previous prepends
		# an extra / i.e. //. The sed command later can't find a
		# Proto_Path with // and therefore will not substitute the
		# correct build_Path resulting in the backout pkg not being
		# created.

		if [ "$CLIENT_BASEDIR" = "/" ]; then
			Client_Path=`echo $Client_Path | sed 's|^\/\/|\/|'`
			Proto_Path=`echo $Proto_Path | sed 's|^\/\/|\/|'`
		fi
			
		# Note: If the file isn't really there, pkgproto
		# doesn't write anything but displays an error
		# so check for the file before processing.

		if [ -f "$Proto_Path" ]; then
			LINE=`pkgproto $Proto_Path=$path`
		else
			continue
		fi

		ftype=`echo $LINE | nawk '{ print $1 }'`
		if [ "$ftype" = "f" ]; then
			Reg_File=1
		fi

		if [ $Reg_File = 1 ]; then
			# Add source file to the prototype entry
			if [ "$Proto_Path" = "$path" ]; then
				LINE=`echo $LINE | sed -e "s|$Proto_Path|$Build_Path|2"`
			else
				LINE=`echo $LINE | sed -e "s|$Proto_Path|$Build_Path|"`
			fi

			DirName=`dirname $Build_Path`
			# make room in the build tree
			mkdir -p $DirName
			cp -p $Proto_Path $Build_Path
		fi

		# Insert it into the prototype file
		echo $LINE 1>>$PROTO_FILE 2>/dev/null

		# Remove the file only if it's OK'd by removef
		rm `removef $PKGINST $Client_Path` 1>/dev/null 2>&1
	done
	removef -f $PKGINST

	rm $Our_Deletes
fi

#
# Unless specifically denied, make the backout package.
#
if [ "$PATCH_NO_UNDO" != "true" ]; then
	cd $BUILD_DIR	# We have to build from here.

	if [ "$PATCH_UNDO_ARCHIVE" != "none" ]; then
		STAGE_DIR="$PATCH_UNDO_ARCHIVE"
		ARCHIVE_DIR="$PATCH_UNDO_ARCHIVE/$SUNW_PATCHID/$PKGINST"
		mkdir -p $ARCHIVE_DIR
		mkdir -p $PKGSAV/$SUNW_PATCHID
	else
		if [ -d $PKGSAV/$SUNW_PATCHID ]; then
			rm -r $PKGSAV/$SUNW_PATCHID
		fi
		STAGE_DIR=$PKGSAV
		ARCHIVE_DIR=$PKGSAV/$SUNW_PATCHID
		mkdir $ARCHIVE_DIR
	fi

	pkgmk -o -d $STAGE_DIR 1>/dev/null 2>&1
	pkgtrans -s $STAGE_DIR $ARCHIVE_DIR/undo $PKG 1>/dev/null 2>&1
	compress $ARCHIVE_DIR/undo
	retcode=$?
	if [ "$retcode" != 0 ]; then
		echo "compress(1) returned error code $retcode"
		echo "The $PKGINST backout package will not be compressed."
		echo "Continuing to process backout package."
	fi
	if [ "$PATCH_UNDO_ARCHIVE" != "none" ]; then
		if [ $retcode != 0 ]; then
			build_remote_file "undo"
		else
			build_remote_file "undo.Z"
		fi
	fi
	rm -r $STAGE_DIR/$PKG

	cd ..
	rm -r $BUILD_DIR
	# remove the scripts that are left behind
	install_scripts=`dirname $0`
	rm $install_scripts/checkinstall $install_scripts/patch_checkinstall $install_scripts/patch_postinstall
fi

#
# Since this apparently worked, we'll mark as obsoleted the prior
# versions of this patch - installpatch deals with explicit obsoletions.
#
cd ${PKG_INSTALL_ROOT:-/}
cd var/sadm/pkg

active_base=`echo $SUNW_PATCHID | nawk '
	{ print substr($0, 1, match($0, "-")-1) } '`

List=`ls -d $PKGINST/save/${active_base}* 2>/dev/null`
if [ $? -ne 0 ]; then
	List=""
fi

for savedir in $List; do
        patch=`basename $savedir` 
        if [ $patch = $SUNW_PATCHID ]; then
		break
	fi

        # If we get here then the previous patch gets deleted
	if [ -f $savedir/undo ]; then
		mv $savedir/undo $savedir/obsolete
		echo $SUNW_PATCHID >> $savedir/obsoleted_by
	elif [ -f $savedir/undo.Z ]; then
		mv $savedir/undo.Z $savedir/obsolete.Z
		echo $SUNW_PATCHID >> $savedir/obsoleted_by
        elif  [ -f $savedir/remote ]; then
                `grep . $PKGSAV/$patch/remote | sed 's|STATE=.*|STATE=obsolete|' > $TEMP_REMOTE` 
                rm -f $PKGSAV/$patch/remote 
                mv $TEMP_REMOTE $PKGSAV/$patch/remote  
                rm -f $TEMP_REMOTE 
                echo $SUNW_PATCHID >> $savedir/obsoleted_by
	elif  [ -f $savedir/obsolete -o -f $savedir/obsolete.Z ]; then
		echo $SUNW_PATCHID >> $savedir/obsoleted_by
	fi
done

# If additional operations are required for this package, place
# those package-specific commands here.

#XXXSpecial_CommandsXXX#

# GK NOTE: The entire SUNWscr/postinstall script has been 
#          included in this patch revision to make future
#          change more reliable. The sections which are not 
#          to be executed when the patch is installed are 
#          commented out.

#
#ident	"@(#)postinstall	1.21	02/10/07 SMI"
#
# Copyright (c) 1996-2002 by Sun Microsystems, Inc.
# All rights reserved.
# Use is subject to license terms.
#
#

###########################################################################
#
# postinstall for SUNWscr
#
#	* Update ${BASEDIR}/etc/devlinks
#	(* Add DID driver: moved to scinstall)
#	* Make ${BASEDIR}/global/.devices/node@${nodeid} directories
#	* Insert "sd_retry_on_reservation_conflict=0" in sd.conf
#	* Insert "sd_retry_on_reservation_conflict=0" in ssd.conf
#	* Add appropriate lines to /etc/system
#       * Update /etc/iu.ap file to include clhbsndr for public net devices
#
###########################################################################

SC_MAXNODEID=64

PKGNAME=SUNWscr
STARTTAG="Start of lines added by ${PKGNAME}"
  ENDTAG="End   of lines added by ${PKGNAME}"
PROG=${PKGNAME}.postinstall

TMPFILE1=/tmp/devlink_update.$$
TMPFILE2=/tmp/new.iu.ap.$$
PUBLIC_NETWORK_DEVICES="hme qfe eri ge ce"


###########################################
#
# Cleanup any temporary files on exit/interrupt
#
###########################################
cleanup()
{
	exit_code=$1

	if [ "${TMPFILE1}" ]; then
		rm -f ${TMPFILE1}
	fi

	if [ -f "${TMPFILE2}" ]; then
		rm -f ${TMPFILE2}
	fi

	exit ${exit_code}
}

###########################################
#
# remove_SUNWscr_edits <filename>
#
#	Backout all lined from the given ascii <filename>
#	indicated by the SUNWscr comment tag lines.
#
###########################################
remove_SUNWscr_edits()
{
	update_file=$1

	while :
	do
		grep "${STARTTAG}" ${update_file} >/dev/null 2>&1
		case $? in
		2)	# error reading file
			echo "${PROG}:  error reading ${update_file}"
			return 1
			;;

		0)	# grep found the string, so get rid of the entries
			ed -s ${update_file} << EOF >/dev/null 2>&1
/${STARTTAG}/,/${ENDTAG}/d
w
q
EOF
			if [ $? -ne 0 ]; then
				echo "${PROG}: problem updating ${update_file}"
				return 1
			fi
			;;

		*)
			break
			;;
		esac
	done

	return 0
}

###########################################
#
# add entries to /etc/devlinks.tab
#
###########################################
update_etc_devlinks()
{
	update_file=${BASEDIR}/etc/devlink.tab

	# remove the old entries
	remove_SUNWscr_edits ${update_file}

	# remove any errant did entries
	grep -v "^type=ddi_pseudo;name=did;minor" ${update_file} > ${TMPFILE1}

	if [ ! -s ${TMPFILE1} ]
	then
		return 1
	fi
	mv ${TMPFILE1} ${update_file}

	# add the new entries to the copy
cat << EOF >> ${update_file}
# ${STARTTAG}
type=ddi_pseudo;name=did;minor=admin	did/admin
type=ddi_pseudo;name=did;minor3=blk	did/dsk/d\M2
type=ddi_pseudo;name=did;minor3=raw	did/rdsk/d\M2
type=ddi_pseudo;name=did;minor3=tp	did/rmt/\M2
# ${ENDTAG}
EOF

	if [ $? -ne 0 ]; then
		echo "${PROG}: unable to update ${update_file}"
		return 1
	fi

	return 0
}

###########################################
#
# Make /global/.devices/node@<ID> directories.
# /global and /global/.devices should have already
# been created as a result of entries in the package map.
#
###########################################
make_globaldevdirs()
{
	nodeid=1
	mkdirerrs=0
	chgerr=0
	dir=

	while [ ${nodeid} -le ${SC_MAXNODEID} ]
	do
		dir=${BASEDIR}/global/.devices/node@${nodeid}
		if [ ! -d ${dir} ]; then
			mkdir -m 0755 ${dir}
			if [ $? -ne 0 ]; then
				mkdirerrs=`expr ${mkdirerrs} + 1`
				echo "${PROG}: failed to mkdir ${dir}"
			else
				chgerr=0
				chown root ${dir} || `expr ${chgerr} + 1`
				chgrp sys  ${dir} || `expr ${chgerr} + 1`
				if [ ${chgerr} -ne 0 ]; then
					mkdirerrs=`expr ${mkdirerrs} + 1`
					echo "${PROG}: failed to change group/owner for ${dir}"
				fi
			fi
		fi

		nodeid=`expr ${nodeid} + 1`
	done

	return ${mkdirerrs}
}

###########################################
#
# Insert "sd_retry_on_reservation_conflict=0"
# in sd.conf or ssd.conf.  The SCSI disk driver
# must not do retries when encountering reservation
# conflict conditions.
#
###########################################
update_sd_conf()
{
	update_file=$1

	# If sd.conf or ssd.conf do not exist, we are done
	if [ ! -f "${update_file}" ]; then
		return 0
	fi

	# remove the old entries
	remove_SUNWscr_edits ${update_file}

	# insert the new line near the top of the file
	ed -s ${update_file} << EOF >/dev/null 2>&1
/name=/i

# ${STARTTAG}
sd_retry_on_reservation_conflict=0;
# ${ENDTAG}

.
w
q
EOF

	# report any errors
	if [ $? -ne 0 ]; then
		echo "${PROG}: problem updating ${update_file}"
		return 1
	fi

	return 0
}

###########################################
#
###########################################
update_etc_system()
{
	update_file=${BASEDIR}/etc/system

	# remove the old entries
	remove_SUNWscr_edits ${update_file}

	# add the new entries
cat << EOF >> ${update_file}
* ${STARTTAG}
set rpcmod:svc_default_stksize=0x6000
set ge:ge_intr_mode=0x833
* ${ENDTAG}
EOF

	if [ $? -ne 0 ]; then
		echo "${PROG}: unable to update ${update_file}"
		return 1
	fi

	return 0
}

###########################################
#
# Set up a link in the rcS.d directory for
# the did_update_vfstab. This will remove
# itself after it has run once in clustered
# mode.
#
###########################################
link_did_rcscript()
{
	ln ${BASEDIR}/etc/init.d/did_update_vfstab ${BASEDIR}/etc/rcS.d/S68did_update_vfstab

	if [ $? -ne 0 ]; then
		echo "${PROG}: problem linking did_update_vfstab"
		return 1
	fi

	return 0
}

###########################################
#
# Update /etc/iu.ap file. Known public network
# devices will be configured to have the clhbsndr
# streams module autopushed.
#
###########################################
update_etc_iu_ap()
{
	update_file=${BASEDIR}/etc/iu.ap

	# If /etc/iu.ap does not exist, create it
	if [ ! -f "${update_file}" ]; then
		cat << EOF >> ${update_file}
#
# Autopush setup
#

EOF
		if [ $? -ne 0 ]; then
			echo "${PROG}: problem updating ${update_file}"
			return 1
		fi
	fi

	# remove the old entries
	remove_SUNWscr_edits ${update_file}

	#
	# Add an entry for each know public network device to the the
	# /etc/iu.ap file. The streams module clhbsndr is configured to
	# be pushed right above the device driver. If an entry already
	# exists, the entry is updated to include the clhbsndr module.
	# The following awk script creates the new /etc/iu.ap file after
	# consulting the existing file. The main block updates existing
	# entries. The END block adds entries for devices that did not
	# already exist in the file.
	#
	awk 'BEGIN {modified = 0; ndevs = 0} \
		{ \
			if (NR == 1) ndevs = split(devices, dev, " "); \
			for (i = 1; i <= ndevs; i++) { \
				if ($1 == dev[i]) { \
					found[dev[i]] = 1 \
				} \
			} \
			if (found[$1] != 1) { \
				print \
			} else if ($4 != "clhbsndr") { \
				modified++; \
				for (i = 1; i <= 3; i++) printf("\t%s", $i); \
				printf("\tclhbsndr"); \
				for (i = 4; i <= NF; i++) printf(" %s", $i); \
				printf("\n"); \
			} else { \
				print \
			} \
		} \
	     END   { \
			if (ndevs == 0) ndevs = split(devices, dev, " "); \
			printf("# %s\n", st); \
			if (modified > 0) { \
				printf("# In addition to these new lines,"); \
				printf(" some preexisting lines above\n"); \
				printf("# might have been modified to"); \
				printf(" include the module clhbsndr\n"); \
			} \
			for (i = 1; i <= ndevs; i++) { \
				if (found[dev[i]] != 1) { \
					printf("\t%s\t-1\t0\tclhbsndr\n", dev[i]) \
				} \
			} \
			printf("# %s\n", et) \
		}' "devices=$PUBLIC_NETWORK_DEVICES" "st=$STARTTAG" \
			"et=$ENDTAG" ${update_file} > ${TMPFILE2} \
			2>/dev/null

	if [ $? -ne 0 ]; then
		echo "${PROG}: problem updating ${update_file}"
		return 1
	fi

	mv -f ${TMPFILE2} ${update_file}

	if [ $? -ne 0 ]; then
		echo "${PROG}: problem updating ${update_file}"
		return 1
	fi

	return 0
}

###########################################
#
# main
#
###########################################
errs=0

# catch common signals
trap 'echo "${PROG}: caught signal";  cleanup 3' 1 2 3 15

#update_etc_devlinks	|| errs=`expr ${errs} + 1`
#make_globaldevdirs	|| errs=`expr ${errs} + 1`
#update_sd_conf ${BASEDIR}/kernel/drv/sd.conf	|| errs=`expr ${errs} + 1`
#update_sd_conf ${BASEDIR}/kernel/drv/ssd.conf	|| errs=`expr ${errs} + 1`
update_etc_system	|| errs=`expr ${errs} + 1`
#link_did_rcscript	|| errs=`expr ${errs} + 1`
update_etc_iu_ap        || errs=`expr ${errs} + 1`

# make sure next reboot is a reconfig reboot
# touch ${BASEDIR}/reconfigure

if [ ${errs} -ne 0 ]; then
	cleanup 1
else
	cleanup 0
fi

exit 0
