#!/bin/sh

# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
#ident	"@(#)patch-finish.sh	1.2	08/04/14 SMI"

. /lib/svc/share/smf_include.sh

LC_ALL=C; export LC_ALL

DELETE_LIST=/var/sadm/patch/.delete_list

COMM=/usr/bin/comm
RM=/usr/bin/rm
SED=/usr/bin/sed
SORT=/usr/bin/sort

delete ()
{
	if [ -f $DELETE_LIST ]; then
		# Found the list of files to delete

		SORTED_CONTENTS=/var/run/.sorted.contents.$$
		SORTED_DELETES=/var/run/.sorted.deletes.$$

		# We take just the first column of contents(4)
		# database and sort them as order.
		$SED -e '/ d none / d' -e 's/[= ].*//' \
		    /var/sadm/install/contents |$SORT > $SORTED_CONTENTS

		# Sort the delete list as well
		$SORT $DELETE_LIST > $SORTED_DELETES

		# Make sure path isn't registered in contents database.
		# If its registered, then don't delete it and log a
		# warning.  Otherwise, go ahead and delete it.
		# comm(1) picks the common entries in both lists.
		$COMM -12 $SORTED_CONTENTS $SORTED_DELETES |\
		     while read path ; do
			# Path exists in the contents database.
			echo "Warning: Registered file, <$path>" \
			    "will not be removed from the system."
		done

		# Delete the named file path.  The deletes
		# file does not have directories in it, so
		# we don't need to handle cases where path
		# is a dir. comm(1) picks the entries which
		# exist only in the delete list.
		$COMM -13 $SORTED_CONTENTS $SORTED_DELETES |\
		     while read path ; do
			$RM -f $path
		done

		# Remove delete list file.
		$RM -f $DELETE_LIST $SORTED_CONTENTS $SORTED_DELETES
	fi
}

case "$1" in
'delete')
	# Cleanup up the files that need to be deleted
	delete

	# Disable this service so that it doesn't run again.
	/usr/sbin/svcadm disable system/patch-finish:delete
	if [ $? -ne 0 ] ; then
		exit $SMF_EXIT_ERR_CONFIG
	fi
	;;
*)
	echo "Usage: $0 { delete }"
	exit $SMF_EXIT_ERR_CONFIG
	;;
esac


exit $SMF_EXIT_OK
