#!/bin/ksh

kbtrans_patch=118859-01

rmpkg=SUNWckr
addpkg=SUNWusb
kbtrans=/kernel/misc/sparcv9/kbtrans

last_patch() {

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

	root_dir=${ROOTDIR:-/}

	## parse id and rev
	pid=`echo $1 | cut -d\- -f1`
	prev=`echo $1 | cut -d\- -f2`
	patch_cnt=0

	## get all installed refernces to the installed patch base id	
	installed_patches=`showrev -R $root_dir -p | sed -n -e 's/Req.*//' -e 's/[a-zA-Z]*://g' -e 's/,//g' -e "/$pid/p"`
	
	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
}


restore_kbtrans() {


	## This patch will add kbtrans to SUNWckr.  Manually remove it from SUNWusb
	## if it exists
	##

	if [ ! -f $ROOTDIR/$kbtrans ] ; then
		return
	fi
	last_patch $kbtrans_patch
	if [ "$?" = "0" ] ; then 
		pkg=`pkgchk -R $ROOTDIR -l -p $kbtrans | grep $rmpkg`
		if [ "$?" =  "0" ] ; then
			removef -R $ROOTDIR $rmpkg $ROOTDIR/$kbtrans 1>/dev/null 2>&1
			removef -R $ROOTDIR -f $rmpkg
			installf -R $ROOTDIR $addpkg $ROOTDIR/$kbtrans 1>/dev/null 2>&1
			installf -R $ROOTDIR -f $addpkg
		fi
	fi
}

if [ "$ROOTDIR" != "/" ]; then
    	# Handle diskless, alternate root case.
	restore_kbtrans
    	return
fi

if [ -x '/usr/bin/zonename' ] ; then
	if [ `/usr/bin/zonename` != "global" ] ; then
		# We are in a local zone
		# kbtrans is taken care of in global zone.
		return
	else
		# In a global zone
		restore_kbtrans
	fi
else
  	# we are in the global zone or on a system
   	# without zones support.
   	restore_kbtrans
fi
