#!/bin/ksh

PLATFORM=$(/usr/bin/uname -m)
THIS_PATCH=116561-08

last_patch() {

	typeset -r this_patch=$1

	## returns the number of patches installed at or above this rev.

	typeset -r root_dir=${ROOTDIR:-/}

	## parse id and rev
	typeset -r pid=$(echo $this_patch  | cut -d\- -f1)
	typeset -r prev=$(echo $this_patch | cut -d\- -f2)
	integer patch_cnt=0

	## get all installed refernces to the installed patch base id
	typeset -r installed_patches=$(showrev -R $root_dir -p | \
					sed -n -e 's/Req.*//' \
					-e 's/[a-zA-Z]*://g'  \
					-e 's/,//' -e "/$pid/p")

	typeset base= rev=
	for x in $installed_patches ; do
		base=`echo $x  | cut -d\- -f1`
		rev=`echo $x | cut -d\- -f2`
		if [ $pid -eq $base ] && [ $rev -ge $prev ] ; then
			## count all installed patches includeing this patch
			patch_cnt=$(($patch_cnt + 1))
		fi
	done

	return $patch_cnt
}

Quiet() {
	typeset -r cmd_n_args=$*
	eval "$cmd_n_args" > /dev/null 2>&1
}

rem_dir() {

	typeset -r dir=$1
	typeset -r pkg=$2

	[ -z "$dir" ] && return 1

	if [ -d $ROOTDIR/$dir ] ; then
		if [ "$?" = "0" ] ; then
			Quiet removef -R $ROOTDIR $pkg $ROOTDIR/$dir/*
			Quiet removef -R $ROOTDIR $pkg $ROOTDIR/$dir
			Quiet removef -R $ROOTDIR -f $pkg
		fi
                /usr/bin/rm -rf $ROOTDIR/$dir
	fi

}

restore_link() {

	typeset -r link=$ROOTDIR/$1
	typeset -r linkto=$2
	typeset -r pkg=$3

	[ -a $link ] && return 0

	## if there is no link or directory, then restore orig link
	if [ $PLATFORM = "sun4u" ]; then
		Quiet installf -R $ROOTDIR $pkg $link=$linkto s
		cd `dirname $link`
		ln -s $linkto
		Quiet installf -f -R $ROOTDIR $pkg
	fi
}

last_patch $THIS_PATCH && {
	rem_dir usr/platform/SUNW,Netra-CP2300/include SUNWhea
	rem_dir usr/platform/SUNW,Netra-CP2300/sbin SUNWkvm

	restore_link usr/platform/SUNW,Netra-CP2300/include \
			../sun4u/include SUNWhea
	restore_link usr/platform/SUNW,Netra-CP2300/sbin \
			../sun4u/sbin SUNWkvm
}

exit 0
