#! /bin/sh
#
#ident	"@(#)preremove	1.5	03/08/14 SMI"
#
# Copyright 1996-2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
#

###########################################################################
#
# preremove for SUNWscr
#
#	* Remove ${BASEDIR}/global/.devices/node@${nodeid} directories
#	* Remove clhbsndr entries from ${BASEDIR}/etc/iu.ap file
#
###########################################################################

PATH=/usr/bin:/usr/sbin
export PATH

PKGNAME=SUNWscr
PROG=${PKGNAME}.preremove

SC_MAXNODEID=64

TMPFILE=/tmp/new.iu.ap.$$

###########################################
#
# Cleanup any temporary files on exit/interrupt
#
###########################################
cleanup()
{
        exit_code=$1

        if [ -f "${TMPFILE}" ]; then
                rm -f ${TMPFILE}
        fi

        exit ${exit_code}
}

###########################################
#
# Remove /global/.devices/node@<ID> directories.
# /global and /global/.devices will be removed
# as a result of entries in the package map.
#
###########################################
remove_globaldevdirs()
{
	nodeid=1
	dir=

	while [ ${nodeid} -le ${SC_MAXNODEID} ]
	do
		dir=${BASEDIR}/global/.devices/node@${nodeid}
		rmdir ${dir} 2>/dev/null
		nodeid=`expr ${nodeid} + 1`
	done

	return 0
}

###########################################
#
# Update /etc/iu.ap file.
# Remove autopush clhbsndr. 
#
###########################################
update_etc_iu_ap()
{
        # If /etc/iu.ap does not exist, we are done
        if [ ! -f "${BASEDIR}/etc/iu.ap" ]; then
		return 0
        fi

        awk '{ \
		hbindex = -1; \
		for (i = 1; i <= NF; i++) { \
			if ($i == "clhbsndr") { \
				hbindex = i; \
				break \
			} \
		} \
		if (hbindex == -1) { \
			print \
		} else if (NF > 4) { \
			for (i = 1; i < 4; i++) printf("\t%s", $i); \
			printf("\t"); \
			for (i = 4; i < hbindex; i++) printf(" %s", $i); \
			for (i = hbindex + 1; i <= NF; i++) printf(" %s", $i); \
			printf("\n") \
		} \
	}' ${BASEDIR}/etc/iu.ap > ${TMPFILE} 2>/dev/null

        if [ $? -ne 0 ]; then
                echo "${PROG}: problem restoring /etc/iu.ap"
                return 1
        fi

        mv -f ${TMPFILE} ${BASEDIR}/etc/iu.ap

        if [ $? -ne 0 ]; then
                echo "${PROG}: problem restoring /etc/iu.ap"
                return 1
        fi

        return 0
}


###########################################
#
# main
#
###########################################
errs=0

# catch common signals
trap 'echo "${PROG}: caught signal";  cleanup 3' 1 2 3 15

remove_globaldevdirs	|| errs=`expr ${errs} + 1`
update_etc_iu_ap	|| errs=`expr ${errs} + 1`

if [ ${errs} -ne 0 ]; then
        cleanup 1
else
        cleanup 0
fi
