#!/bin/ksh

## This script removes all occurances of SUNW_PKG_DIR from
## installed pkginfo files and any backout package that exists.

PATH=/usr/bin:$PATH
export PATH

WD=/tmp/$PatchNum.$$

[[ ! -d $WD ]] && mkdir -p -m 644 $WD || exit 1

cd $ROOTDIR/var/sadm/pkg	|| exit 1

update_pkgmap() {
	typeset -r pkg=$1
	typeset -r pkginfo_sum=$(sum $pkg/pkginfo | awk '{print $1}')
	typeset -r pkginfo_sz=$(wc -c $pkg/pkginfo | awk '{print $1}')

	typeset -r tmpfile=$WD/pkgmap.$$
	nawk -v pi="$pkginfo_sz" -v pm="$pkginfo_sum" '
		$3 ~ /pkginfo/ {
			printf("%s %s %s %s %s %s\n", \
				$1, $2, $3, pi, pm, $6)
		}
		$3 !~ /pkginfo/ {
			print
		}' $pkg/pkgmap > $tmpfile   || return $?
	mv -f $tmpfile $pkg/pkgmap	  || return $?
	return 0
}

echo "Modifying pkginfo files..."

for pinfo in */pkginfo; do
	if grep "SUNW_PKG_DIR=" $pinfo >/dev/null 2>&1; then
		sed '/SUNW_PKG_DIR=/d' $pinfo > $pinfo.$$  || exit 1
		mv $pinfo.$$ $pinfo	|| exit 1
	fi
done

echo "Modifying backout packages..."

undoPkgs=$(find . \( -name undo\.Z -o -name undo -o -name obsolete\.Z -o -name obsolete \) -print)

for bopkg in $undoPkgs; do
	pkgname=$(basename $bopkg)
	dir=$(dirname $bopkg)
	pkg=$(echo $bopkg | nawk -F/ '{print $2}')
	strmPkg=${bopkg%.*}
	if [[ -z "$strmPkg" ]]; then
		strmPkg=$bopkg
	else
		uncompress $bopkg > /dev/null 2>&1
	fi
	if grep "SUNW_PKG_DIR=" $strmPkg > /dev/null 2>&1; then
		if [ -z "$PKG_INSTALL_ROOT" ] ; then
			PKG_INSTALL_ROOT="/"
		fi

		pkg1=`pkgparam -R $PKG_INSTALL_ROOT $pkg PKG`
		if [ $? -ne 0 ]
		then
			 echo "pkgparam : Error in retrieving PKG parameter value"
			  exit 1
		fi
		pkg=$pkg1
		pkgtrans -o $strmPkg $WD $pkg > /dev/null 2>&1
		sed '/SUNW_PKG_DIR=/d' $WD/$pkg/pkginfo > $WD/$pkg/pkginfo.$$ \
				|| exit 1
		mv $WD/$pkg/pkginfo.$$ $WD/$pkg/pkginfo  || exit 1
		update_pkgmap $WD/$pkg || exit 1
		pkgtrans -o -s $WD $strmPkg $pkg > /dev/null 2>&1
	fi
	compress $strmPkg > /dev/null 2>&1
done

rm -fr $WD
exit 0

