# checkinstall script to validate backing out a patch.
# directory format option.
#
#pragma ident	"@(#)patch_checkinstall	1.5	10/03/05 SMI"
#
# Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

# Definitions for override safety mechanism
PATCH_OVERRIDE_LIB="${PKG_INSTALL_ROOT}/usr/lib/patch/patch_override_lib"

# Check if we messaging is ready. Returns 0 on success, 1 on failure
# On successful run it leaves MSG_FILENAME variable defined
# 
# Usage:
#
# check_patch_script_messaging
#
check_patch_script_messaging()
{
	TMP_DIRNAME="/var/run"
	MSG_FILENAME="${TMP_DIRNAME}/patchrm_msg_file_${ACTIVE_PATCH}"

	if [ -w "${MSG_FILENAME}" ] ; then
		unset TMP_DIRNAME
		return 0
	else
		unset TMP_DIRNAME
		unset MSG_FILENAME
		return 1
	fi
}

# This function prepares a message to be printed to stdout towards the end
# of postpatch execution. If the message file is not ready, it at least tries
# immediate output to stdout which is currently know to work only in patch
# level scripts.
#
# Usage:
#
# print_patch_message "text_of_message_to_be_printed_out"
#
print_patch_message()
{
	if check_patch_script_messaging; then
		echo "$*" >> "${MSG_FILENAME}"
	else
		echo "$*"
	fi

	return 0
}

# script in a fucntion so that it can be overridden if needed.
patch_checkinstall()
{
	PATH=/usr/sadm/bin:$PATH

	LATER_MSG="PaTcH_MsG 6 ERROR: A later version of this patch is applied."
	NOPATCH_MSG="PaTcH_MsG 2 ERROR: Patch number $ACTIVE_PATCH is not installed"
	NEW_LIST=""

	# Get OLDLIST
	. $1

	#
	# Confirm that the patch that got us here is the latest one installed on
	# the system and remove it from PATCHLIST.
	#
	Is_Inst=0
	Skip=0
	active_base=`echo $ACTIVE_PATCH | nawk '
		{ print substr($0, 1, match($0, "-")-1) } '`
	active_inst=`echo $ACTIVE_PATCH | nawk '
		{ print substr($0, match($0, "-")+1) } '`
	for patchappl in ${OLDLIST}; do
		appl_base=`echo $patchappl | nawk '
			{ print substr($0, 1, match($0, "-")-1) } '`
		if [ $appl_base = $active_base ]; then
			appl_inst=`echo $patchappl | nawk '
				{ print substr($0, match($0, "-")+1) } '`
			result=`expr $appl_inst \> $active_inst`
			if [ $result -eq 1 ]; then
				puttext "$LATER_MSG"
				exit 3
			elif [ $appl_inst = $active_inst ]; then
				Is_Inst=1
				Skip=1
			fi
		fi
		if [ $Skip = 1 ]; then
			Skip=0
		else
			NEW_LIST="${NEW_LIST} $patchappl"
		fi
	done

	if [ $Is_Inst = 0 ]; then
		puttext "$NOPATCH_MSG"
		exit 3
	fi

	#
	# OK, all's well. Now condition the key variables.
	#
	echo "PATCHLIST=${NEW_LIST}" >> $1
	echo "SUNW_PATCHID=" >> $1
	echo "PATCH_INFO_$ACTIVE_PATCH=backed out" >> $1

	# remove the used parameters
	echo "ACTIVE_OBSOLETES=" >> $1
	echo "SUNW_OBSOLETES=" >> $1
}

# load the override lib if it exists
if [ -f "${PATCH_OVERRIDE_LIB}" -a -r "${PATCH_OVERRIDE_LIB}" ] ; then
   . "${PATCH_OVERRIDE_LIB}"
fi

# execute the script function
patch_checkinstall "$@"

exit 0

