#!/bin/ksh -hp

# Copyright (c) 2006 by Sun Microsystems, Inc.
# All rights reserved

ZFSPKGS="SUNWzfskr SUNWzfsr SUNWzfsu"

zfs_patch=122641-01
admin=/tmp/admin.$$

quiet() {
cat <<-eof > $admin
	mail=
	instance=nocheck
	partial=nocheck
	runlevel=nocheck
	idepend=nocheck
	rdepend=nocheck
	space=quit
	setuid=nocheck
	conflict=nocheck
	action=nocheck
	eof

chmod a+x $admin

}

	
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=`patchadd -p -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
}

backout_pkgs() {
	last_patch $zfs_patch
	## is this that patch that installed the zfs pkgs?
	if [ "$?" = "0" ] ; then
		## then it is ok to remove them
		quiet
		for zfspkg in $ZFSPKGS ; do
			## is the pkg installed?
			if pkginfo -q -R $ROOTDIR $zfspkg ; then
				## yes, remove it.
				pkgrm -n -a $admin -R $ROOTDIR $zfspkg
			fi
		done
		/bin/rm -f $admin
	fi
}

ExecuteInProperEnvironment () {

PKGCOND=/usr/bin/pkgcond

   if $PKGCOND is_whole_root_nonglobal_zone > /dev/null 2>&1 ; then
       # Execute non-global whole root zone commands.
       # Should be same action as the default action.
       return 0
   fi

   if $PKGCOND is_nonglobal_zone > /dev/null 2>&1 ; then
       # Execute non-global zone commands. Should be no action here
       return 0
   fi

   if $PKGCOND is_netinstall_image > /dev/null 2>&1 ; then
       # Execute commands applicable to patching the mini-root.
       # There are usually no actions to take here since your patching
       # the mini-root on an install server.
       backout_pkgs
       return 0
   fi

   if $PKGCOND is_mounted_miniroot > /dev/null 2>&1 ; then
       # Execute commands specific to the mini-root
       backout_pkgs
       return 0
   fi

   if $PKGCOND is_diskless_client > /dev/null 2>&1 ; then
       # Execute commands specific to diskless client
       backout_pkgs
       return 0
   fi

   if $PKGCOND is_alternative_root > /dev/null 2>&1 ; then
       # Execute commands specific to an alternate root
       backout_pkgs
       return 0
   fi

   if $PKGCOND is_global_zone > /dev/null 2>&1 ; then
       # In a global zone and system is mounted on /.
       # Execute all commands.
       backout_pkgs
       return 0
   fi

} 

ExecuteInProperEnvironment
