#!/bin/bash
set -x
# Author: Dean Wilson
# Created on: 2003/12/18
# Version: 0.4
# Last Updated: 2005/12/18
# changes: Added information to show how long it ran for.
# changes: changed the code to check the binaries

STARTEPOCH=$(date +'%s')

# external binaries. anything that must be present should be added here.
binaries=$(cat<<all_required_binaries
  basename
  expr
  find
  hostname
  logger
  mail
  mktemp
  sort
  uniq
all_required_binaries)

# app settings
APPNAME=$(basename $0)
MAILTO=dwilson@example.org
# anything bigger than the size given will be flagged.
FINDOPTS=' / -size +1024000k'
EXCLUDE=/etc/exclude_bigfiles.conf

# sanity checks.
for required_binary in $binaries; do
  which $required_binary > /dev/null
  if [ "$?" != '0' ];then
    printf "$APPNAME: No usable '$required_binary' in '$PATH'\n"
    exit 1
  fi
done

# get the handle to use to hold the results
TMPFILE=$(mktemp -q /tmp/$APPNAME.XXXXXX)

if [ $? -ne 0 ]; then
  echo "$APPNAME: Can't create temp file, exiting..."
  exit 2
fi

# get the new files.
UNIQTMPFILE=$(mktemp -q /tmp/$APPNAME.XXXXXX)

if [ $? -ne 0 ]; then
  echo "$APPNAME: Can't create temp file, exiting..."
  exit 3
fi

# build up the subject line
HOSTNAME=$(hostname)
DATE=$(date +'%Y-%m-%d')


# get the big files and put them in a temp file.
find $FINDOPTS > $TMPFILE 2>/dev/null

if [ -e "$EXCLUDE" ];then
  cat $TMPFILE $EXCLUDE | sort | uniq -u > $UNIQTMPFILE
  RESULTS=$UNIQTMPFILE
else
  RESULTS=$TMPFILE
fi

# calculate how long it's been running for.
FINISHEPOCH=$(date +'%s')
TOTALTIME=$(expr $FINISHEPOCH - $STARTEPOCH)

SUBJECT="Big file check from '$HOSTNAME' on $DATE : $TOTALTIME seconds"

if [ -s "$RESULTS" ];then
  #send the remains
  cat $RESULTS | mail -s "$SUBJECT" $MAILTO
  logger -i -p local0.notice -t $APPNAME "Run completing. Mail sent. $TOTALTIME seconds"
else
  logger -i -p local0.notice -t $APPNAME "Run completing. No mail sent. $TOTALTIME seconds"
fi

# clean up.
rm $TMPFILE
rm $UNIQTMPFILE
