#!/bin/sh
#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# ident	"@(#)S20_apply_patches.sh	1.1	08/05/06 SMI"
#

# This script must run after we fix up the zone binaries (S10_fix_bins) since
# the patchadd operation will fail if we are zlogged in to the zone and we
# don't have the fixed up version of the /sbin/sulogin command.
#
# When attempting to add a patch, patchadd can exit non-0 for a variety
# of reasons, many of which we want to ignore since these won't really be
# errors.  For example:
#	2  Attempt to apply a patch that's already been applied
#	6  Patch is obsoleted
#	8  Attempting to patch a package that is not installed
#	24 An incompatible patch is applied
#	35 Later revision already installed
# Instead, we will check for specific error exits from patchadd and fail
# for those cases but tolerate any other error.  These are the errors we
# explicitly check for:
#	18 Not enough space in the file systems
#	25 A required patch is not applied
#	33 Bad formatted patch file or patch file not found
# Other errors will result in a warning from the install but not a failure.
#
# As part of the p2v module interface there are environment variables set for
# this script (e.g. FILEDIR - path to brand-specific file repository).
# See the p2v script for a full list of variables.
#

MSG_PREFIX="        `basename $0`: "

# Print and log provided text.
progress()
{
	msg="$1"
	shift

	echo "${MSG_PREFIX}${msg}" "$@"
	echo "[`date`] ${MSG_PREFIX}${msg}" "$@" >&2
}

# Install the specified patch
dopatch()
{
	progress "$v_installing" "$1"
	echo "yes" | /usr/sbin/patchadd $1 >&2
	res=$?

	if [ $res -ne 0 ]; then
		if [ $res -eq 2 -o $res -eq 6 -o $res -eq 8 -o \
		    $res -eq 24 -o $res -eq 35 ]; then
			return
		elif [ $res -eq 18 -o $res -eq 25 -o $res -eq 33 ]; then
			exit 1
		else
			progress "$w_err" "$1" "$res"
		fi
	fi
}

v_unpacking=" Unpacking patch: "
v_installing="Installing patch: "
e_notfound="ERROR: Patch not found: "
w_err="WARNING: Adding patch failed with unexpected error: "

d=`pwd`

TMPPATCHDIR=/tmp/patch$$
mkdir $TMPPATCHDIR

cd $FILEDIR/patches
for p in `/usr/bin/grep -v '#' order`
do
	if [ -d $p ]; then
		dopatch $p

	elif [ -f $p.zip ]; then
		cd $TMPPATCHDIR
		progress "$v_unpacking" "$p"
		unzip $FILEDIR/patches/$p.zip >/dev/null 2>&1 || exit 1
		dopatch $p
		cd $FILEDIR/patches
		rm -rf $TMPPATCHDIR/$p

	else
		progress "$e_notfound" "$p" || exit 1
	fi
done

rm -rf $TMPPATCHDIR
cd $d
