#!/bin/ksh
#        
# glargest  09/03/14  dck
#
# Find largest files under a directory.
#
# $Header$
#


PATH=/usr/bin:/etc:/usr/sbin:/usr/local/bin:/usr/sbin/cluster/utilities/:/bin
ErrFile=/tmp/glargest$$.err
DoNotCrossFS="-xdev"
Creation=""
Mode=Modify
DATE_TYPE="MODIFICATION"
StartDir=.
NumFiles=10
Size=250

#_______________________________________________________________________
#	Function to display the usage of this shell script.
#	Display available options (arguments) that can be supplied.
Usage () {				# Start of Usage function
	echo >&2 "\nusage: $(basename $1)\t[-Aah] [-d StartDir] [ -n NumFiles ] [ -s Size ]"
	echo >&2 ""
	echo >&2 "\t-A\tScan All filesystems below StartDir (default=Only scan StartDir)"
	echo >&2 "\t-d\tSearch filesystem starting in StartDir (default=$StartDir)"
	echo >&2 "\t-a\tFiles listed by most recent ACCESS"
	echo >&2 "\t-m\tFiles listed by CREATION date OLDER than 1 year."
	echo >&2 "\t-h\tShow command usage (this info)"
	echo >&2 "\t-n\tDisplay NumFiles largest files (default=$NumFiles)"
	echo >&2 "\t-s\tDisplay files greater than Size blocks (default=$Size, ~125K)"
	echo >&2 ""
}					# End of Usage function


while getopts Aad:hmn:s: Options
do
	case ${Options} in
	[A] )
		DoNotCrossFS=""
		;;
	[a] )
		Mode=Access
		DATE_TYPE="ACCESS"
		;;
	[d] )
		StartDir=${OPTARG}
		if [ ! -d "$StartDir" ]
		then
			echo "** Not a directory:  $StartDir\n"
			Usage $0				# And here's the usage.
			exit 99
		fi
		;;
	[m] )
		Creation="-mtime +360"
		;;
	[n] )
		NumFiles=${OPTARG}
		;;
	[s] )
		Size=${OPTARG}
		;;
	h|\?|\- )
		Usage $0				# And here's the usage.
		exit
		;;
	esac
done

#	Check for additional arguments
shift $(expr "${OPTIND}" - 1)
if [ $# -ne 0 ]		# ${#} should now contain nothing
then
	Usage $0					# And here's the usage.
	exit
fi

# Misc calcs to spiff up the output
SizeInBytes=$(echo "512 * $Size" | bc)
case $StartDir in
\.)
	FullDir=$PWD
	;;
\.[!/]*|[!./]*)
	FullDir=$PWD/$StartDir
	;;
\./*)
	FullDir=$PWD$(expr "$StartDir" : "^.\(.*\)")
	;;
/*)
	FullDir=$StartDir
	;;
esac
DisplayCrossFS="No"
if [ -z "$DoNotCrossFS" ]
then
	DisplayCrossFS="Yes"
fi

echo "\n\t$(date)\n\n\tNumber of files:\t${NumFiles}\n\tFiles greater than:\t${SizeInBytes}\n\tStart in directory:\t${FullDir}\n\tAll subfilesystems:\t$DisplayCrossFS\n\tDates show last file:\t${DATE_TYPE}\n"

cd $FullDir
case $Mode in
Modify)
	find . \( \( -name proc -type d \) -o -fstype nfs \) -prune -o $DoNotCrossFS $Creation -type f -size +$Size -print 2>$ErrFile | xargs -I {} ls -l {} | sort -k 5nr,5 | head -$NumFiles
	;;
Access)
	find . \( \( -name proc -type d \) -o -fstype nfs \) -prune -o $DoNotCrossFS $Creation -type f -size +$Size -print 2>$ErrFile | xargs -I {} ls -l {} | sort -k 5nr,5 | nawk -v NumFiles=$NumFiles 'NR <= NumFiles { $1=""; $2=""; $3=""; $4=""; $5=""; $6=""; $7=""; $8=""; print }' | xargs -I {} ls -utl {}
	;;
esac

echo "\n$(cat $ErrFile 2>/dev/null)\n"
rm -f $ErrFile

exit