#!/bin/sh
#
#    Copyright (c) 2001-2006 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   fwclean
#    Module name: utils/firmware
#
#    This script will scan the following directories and remove 
#	executable files that don't belong to any RPM packages.
#	There are files that don't belong to any packages by 
#	default. This scripts will account for them.
#
#

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

#
# Directories that are scanned.
#
DIRS="
/bin
/sbin
/libexec
/fabos/bin
/fabos/sbin
/fabos/libexec
/fabos/modules
/usr/bin
/usr/sbin
/usr/libexec
/tftpboot
/lib
/etc/fabos/rbac
"

#
#Files that don't belong to any package by default
#
LOOSE_FILES=" 
/bin/rcp
/fabos/libexec/essd
/lib/libc.so
/lib/modules/2.6.14.2
/lib/modules/2.4.2_hhl20
/lib/modules/preferred
/lib/libldap-2.3.so.0
"

usage()
{
	echo "Usage: cleanup [ -n ]"
	echo "	-n: show the obsolete files without removing them."
}

do_cleanup_internal(){
    $VERBOSE "Checking $ROOT$DIR, please wait ..."
    /usr/bin/find $DIR -name "*" -xdev -print | 
	while read FILE ; do
	    case "$LOOSE_FILES_PATTERN" in
	    *:"$FILE":*) continue ;;
	    *) /bin/rpm -qf $FILE > /dev/null 2>&1 && continue
		SUBFILE=${FILE:0:16}
		if [ "$NO_REMOVE" = 0 ]; then
			if [ "$SUBFILE" != "/tftpboot/common" ]; then
				$VERBOSE "--Remove $ROOT$FILE"
				/bin/rm -f "$FILE"  > /dev/null 2>&1
			fi
		elif [ "$NO_REMOVE" = 1 ]; then
			if [ "$SUBFILE" != "/tftpboot/common" ]; then
				$VERBOSE "--Junk $ROOT$FILE"
			fi
		fi
		;;
	    esac
	done
}

# Make this function available to child processes, in particular ones
# started inside chroot
export -f do_cleanup_internal

do_cleanup()
{
	ROOT=$1
	NO_REMOVE=$2
	VERBOSE=$3
	LOOSE_FILES_PATTERN=":$(echo $LOOSE_FILES | tr -s ' \n\t' :):"
	export ROOT NO_REMOVE VERBOSE DIR LOOSE_FILES_PATTERN
	echo Removing unneeded files, please wait ...
	for DIR in $DIRS; do
	    # loop 3 times on each, breaking out if we don't core
	    # This is suppressing the problem in defect 79694
	    # it is not fixing it, just hiding it.
	    for i in 1 2 3 ; do
		( chroot $ROOT bash -c "do_cleanup_internal" ) 2>/dev/null
		[ $? -lt 127 ] && break
		echo "There was a problem cleaning $DIR, retrying"
	    done
	done
	echo "Finished removing unneeded files. "
	echo
}

#
# main routine
#
PRI=0
SEC=0
NO_REMOVE=0
VERBOSE=echo
while getopts hnops opt; do
	case $opt in
		h) usage
	 	   exit 1	
		   ;;
		n) NO_REMOVE=1 
		   ;;
		o) VERBOSE=:
		   ;;
		p) PRI=1
		   ;;
		s) SEC=1
		   ;;
		\?) usage;
		    exit 1
		   ;;
	esac
done

case "$PRI$SEC" in
  00|11)
	do_cleanup / $NO_REMOVE $VERBOSE
	do_cleanup /mnt $NO_REMOVE $VERBOSE
	;;
  01) do_cleanup /mnt $NO_REMOVE  $VERBOSE ;;
  10) do_cleanup / $NO_REMOVE  $VERBOSE ;;
esac

