#!/bin/bash
# check-quotas: jshanley@
#
# v0.5: jshanley@: 08-2008: remove email functionality completely to be safe.
# v0.4: jshanley@: 02-2008: cleanup warning text to be more friendly
# v0.3: jshanley@: 02-2008: added report mode.
# v0.2: jshanley@: 02-2008: check for inodes > 250k as well. Make sure we REALLY have a user on the system
#			as sometimes passwd and cpanel get out of sync. *shrug*
# v0.1: jshanley@: 12-2007: initial cycle; use the quota system to quickly find high disk use/abuse
#
# NOTE: user notifications commented out temporarily

inode_critical="250000" # how many INODES before we want a warning
disk_critical="45"      # how many GIGS of disk use before we want a warning
time_start=$(date +%s)
time_total=0
servername=$(uname -n)
EMAIL_LOG="/tmp/$$.$$.$$.email.log"
ADMIN_LOG="/tmp/$$.$$.$$.admin.log"

ADMIN_EMAIL="process_diskuse@hgfix.com"
USER_EMAIL="jshanley@hostgator.com" # to test.
SILENT=0

print(){
	if [ ! "$SILENT" = "1" ]; then
		echo "$*"
	fi
}


clear_vars() {
        disk_use="0";
        inode_use="0";
        inode_total="0";
        inode_inc="0";
	user_exists=""
}

preflight() {
	if [ ! -f "/root/bin/ui" ]; then
		mkdir -p /root/bin/ &>/dev/null
		chmod 500 /root/bin/ &>/dev/null
		wget http://toolbox.hostgator.com/toolbox/ui -O /root/bin/ui &>/dev/null
		chmod 100 /root/bin/ui
	fi
}

get_owner() {
        if [ -f "/var/cpanel/users/$user" ]; then
          my_owner=$(grep OWNER /var/cpanel/users/$user|awk -F"=" '{print $2}')
          if [ -z $my_owner ]; then echo "Failed to determine OWNER for $user ($my_owner)"; exit 1; fi
          if [ "root" = "${my_owner}" ]; then my_owner=${user} ; fi
        else
          echo "/var/cpanel/users/$user does not exist, though I think it should. Exiting."
          exit 1
        fi
}

get_email() {
        if [ -f "/home/${my_owner}/.contactemail" ]; then
          my_email=$(cat /home/${my_owner}/.contactemail)
          if [ "$my_acct_type" = "Shared" ]; then
            my_email_type="(Owner)"
          elif [ "$my_acct_type" = "Reseller" ] || [ "$my_acct_type" = "Resold" ]; then
            my_email_type="(Reseller)"
          else
            my_email_type="(unknown)"
          fi
          if [ -z $my_email ]; then my_email="unset"; fi
        elif [ -f "/home/${my_username}/.contactemail" ]; then
          my_email=$(cat /home/${my_username}/.contactemail)
          if [ "$my_acct_type" = "Shared" ]; then
            my_email_type="(Owner)"
          else
              my_email_type="(unknown)"
          fi
          if [ -z $my_email ]; then my_email="unset"; fi
        else
          # if .contactemail doesn't exist, it's automatically unset.
          my_email="unset"
        fi

        if [ "$my_email" = "unset" ]; then my_email_type=""; fi
}

install_email_binary() {
                                
  if [ ! -e "/root/bin/email" ]; then
	wget http://toolbox.hostgator.com/binaries/email -O /root/bin/email &>/dev/null
	# if we can't install the email binary, we're screwed anyway.
	if [ "$?" -ne "0" ]; then
		exit 2
	fi
	chmod 100 /root/bin/email &>/dev/null
  fi
}

calc_inode_percent() {
        INODE_PCT=$(echo "scale=2; ${inode_total}/50000*100"|bc)
}

check_quotas() {
	echo
	echo "-- checking users on `uname -n`..."
	echo

for user in `ls /var/cpanel/users/`; do
	clear_vars
        # make sure we have both a homedir and a passwd entry (really really exists) to work with.
        if [ -d "/home/$user" ]; then
                        user_exists=""
                if [ ! -z `grep -E "^${user}:" /etc/passwd` ]; then
                        disk_use=$(quota -sv $user |grep -iE "\/dev\/.*"|awk '{print $2}' | grep -E "[1-9][0-9]G"|sed -e "s/G//g") ;
                        for inode_inc in `quota -v $user|grep -iE "\/dev\/.* [0-9]* [0-9]* [0-9]*"|awk '{print $5}'`; do
                          let "inode_total += ${inode_inc}"
                        done
                fi
        fi

        # Pretty-print results if something matches...

        if [ ! -z "$disk_use" ]; then
                if [ "$disk_use" -ge "$disk_critical" ]; then
                        # echo "$user: ${disk_use}G";
                        printf "%10s %-9s %6s\n" "$user" "$disk_use" "gigs"
			if [ "1" = "$SEND_EMAIL" ]; then
			  install_email_binary
			  get_owner
			  get_email
			  USER_EMAIL="${my_email}"
			  /root/bin/ui $user >> $ADMIN_LOG
			  echo "" >> $ADMIN_LOG
			  echo "Disk use: $disk_use gigs (warning)" >> $ADMIN_LOG
			  cat $ADMIN_LOG| /root/bin/email -s "WARNING: `uname -n`: ${user}: ${disk_use} gigs" -f "security@hostgator.com" -n "Warning" ${ADMIN_EMAIL}
			  rm -f "$ADMIN_EMAIL" &>/dev/null
			fi
                fi ;
        fi

        if [ "$inode_total" -ge "$inode_critical" ]; then
                        # echo "$user: ${inode_total} inodes";
                        printf "%10s %-9s %6s\n" "$user" "$inode_total" "inodes"
			if [ "1" = "$SEND_EMAIL" ]; then
				echo "" > $EMAIL_LOG
				install_email_binary
				get_owner
				get_email
				calc_inode_percent
				USER_EMAIL="${my_email}"

				/root/bin/ui $user |grep -E "Server:|User:|Email:|iNodes|Catchalls:" >> $EMAIL_LOG
				echo "" >> $EMAIL_LOG
USER_EMAIL="${my_email}"
			rm -f "$EMAIL_LOG" &>/dev/null
			fi
        fi
done
}

time_finish() {
	time_finish=$(date +%s)
	((time_total=time_finish - time_start))

	if [ ! -z "$time_total" ]; then
		if [ "$time_total" -gt "0" ]; then
	  	echo
	  	echo "-- scan completed in $time_total seconds"
		fi
	fi
}


case "$1" in
        auto-email)
          SEND_EMAIL="0"
          echo "NOTICE: sending email notifications"
        ;;
        quiet)
          SILENT="1"
        ;;
        *)
        # if there's no args, check the server quotas
        if [ -z "$1" ]; then check_quotas ; else
         # probably a username! If it is, give us a nice print out.
         if [ -d "/home/$1/public_html" ]; then
          clear
          USER=$1;
	  user=${USER}
          DISK_USE=$(quota -sv $USER |grep -iE "/dev/.*"|awk '{print $2}' | grep -E "[1-9][0-9]G"|sed -e "s/G//g");
          SERVER=$(uname -n)
          printf "%10s %-9s\n" "Date:" "`date`"
          printf "%10s %-9s\n" "Server:" "$SERVER"
          printf "%10s %-9s\n" "User:" "$USER"

          for inode_inc in `quota -v $USER|grep -iE "\/dev\/.* [0-9]* [0-9]* [0-9]*"|awk '{print $5}'`; do
            let "inode_total += ${inode_inc}"
          done

          printf "%10s %-9s\n" "iNodes:" "$inode_total"
          if [ ! -z "$DISK_USE" ]; then printf "%10s %-9s\n" "Disk Use:" "$DISK_USE Gigs" ; fi
	  if [ ! -z "${my_email}" ]; then printf "%10s %-9s\n" "Email:" "$my_email"; fi
	  get_owner
          get_email
          if [ "$my_email" != "unset" ]; then printf "%10s %-9s\n" "Email:" "$my_email"; fi

          echo
          echo "Checking folders with > 1,000 files"
          echo
          cd /home/$USER && \
		find /home/$USER/public_html /home/$USER/mail -maxdepth 2 -type d|while read FOLDER; do
                INODES=$(find "$FOLDER"|wc -l);
                echo "$INODES $FOLDER";
          done|sort -rn|grep -E "^[1-9][0-9][0-9][0-9]"

          echo
          print "Checking public_html file size distribution"
          echo
          du -h --max-depth=1 /home/$USER/public_html|grep -E "[0-9][G|M]"|sort -rn

         fi
	fi

        echo
        exit 0
        ;;
esac

check_quotas
time_finish

