#!/bin/ksh
#
# $Revision: 1.4 $ $Date: 2010-11-09 15:11:35-05 $
# $UUID: 31a46065-7dd1-3f41-b27c-bc96ce22c12d $
#
#<dirsize: see how big each top-level group directory is.
# usage: dirsize [etc-file [output-file]]

export PATH=/usr/local/bin:/bin:/usr/bin
export BLOCKSIZE=1m
export BLOCK_SIZE=1048576        # BLOCK* sets du output to Mbytes.

umask 022
tag=$(basename $0)
host=$(hostname | cut -f1 -d.)
out='/var/adm/sa/du'

# Format output in consistent-width columns.
# Argument is the number of columns you want.
layout () {
    case "$#" in
        0) k=1 ;;
        *) k=$1 ;;
    esac

    case "$k" in
        [1-9]) ;;
        *) echo 'layout botch'; exit 1 ;;
    esac

    awk '{printf "%6s %s\n", $1, $2}' | pr -o1 -w88 -${k}t | expand
}

say () {
    echo; echo "$(date '+%Y-%m-%d %T'): $*"; echo
}

warn () {
    echo "WARN: $(date '+%Y-%m-%d %T'): $*"
}

logmsg () {
    logger -t $tag -p local1.info "$@"
}

die () {
    logmsg "FATAL: $*"; exit 1
}

# Check the input settings file.  Set an optional output file.
ofile=
case "$#" in
    0) ifile="/usr/local/etc/$tag" ;;
    1) ifile="$1" ;;
    2) ifile="$1"; ofile="$2" ;;
esac
test -f "$ifile" || die "$ifile not found"

# Figure out the date.
logmsg start
set X $(date "+%Y %m%d"); shift
yr=$1
mday=$2

# Set up the output file.
test -d "$out/$yr" || mkdir -p $out/$yr
test -d "$out/$yr" || die "unable to mkdir $out/$yr"

# Redirect all stdout and stderr output.
case "$ofile" in
    "") ofile="$out/$yr/$mday" ;;
    *)  ;;
esac

exec > $ofile
exec 2>&1

# Real work starts here.  Read the directories, columns, etc.
grep '^[1-9]' $ifile | while read depth columns dir
do
    if test -d "$dir"
    then
        say Directory $dir
    else
        warn "$dir: not a directory"
        continue
    fi

    # NOTE: after awk, we could put "sort -nr" or "cat" depending
    # on whether you wanted output sorted by directory size.
    # Ignore anything under 10 Mb.
    (
      cd $dir
      find . -mindepth $depth -maxdepth $depth -type d -print |
          sort | tr '\012' '\000' | xargs -0 du -s |
          awk '{ if ($1 > 9) print }' |
          layout $columns |
          sed -e 's! ./! !g'
    )
done

say done
logmsg done
exit 0
