#! /bin/bash
# #############################################################################

       NAME_="lowspace"
    PURPOSE_="notify when space on a drive is less then n Megabytes"
   SYNOPSIS_="$NAME_ [-hlx] -i <n> -m <mountpoint> -t <n>s|m|h|d"
   REQUIRES_="standard GNU commands, xmessage"
    VERSION_="1.5"
       DATE_="1999-08-10; last update: 2005-02-28"
     AUTHOR_="Dawid Michalczyk <dm@eonworks.com>"
        URL_="www.comp.eonworks.com"
   CATEGORY_="admin"
   PLATFORM_="Linux"
      SHELL_="bash"
 DISTRIBUTE_="yes"

# #############################################################################
# This program is distributed under the terms of the GNU General Public License

usage () {

echo >&2 "$NAME_ $VERSION_ - $PURPOSE_
Usage: $SYNOPSIS_
Requires: $REQUIRES_
Options:
    -i <n>, an integer referring to % capacity. 
    -m <mountpoint>, name of the mountpoint: /var
    -h, usage and options (this help)
    -l, see this script"
    exit 1
}

shopt -s extglob # enabling extended globbing

# args check
[ $# -eq 0 ] && { echo >&2 missing argument, type $NAME_ -h for help; exit 1; }

# var init
xmsg=

while getopts hlxm:i:t: options; do

    case $options in
        i) mb=$OPTARG ;;
        m) mountpoint=$OPTARG ;;
#        x) xmsg=on ;;
#        t) time=$OPTARG ;;
        h) usage ;;
        l) more $0; exit 1 ;;
       \?) echo invalid argument, type $NAME_ -h for help; exit 1 ;;

    esac

done
shift $(( $OPTIND - 1 ))

# check if required command is in $PATH variable
if [ $xmsg ]; then
    which xmessage &> /dev/null
    [[ $? != 0 ]] && { echo >&2 the required \"xmessage\" command is not in your PATH variable; exit 1; }
fi

# args check
[[ $mountpoint ]] || { echo >&2 the -m option and argument must be specified; exit 1; }
[[ $mb == *[!0-9]* ]] && { echo >&2 the argument to option -i must be an integer; exit 1; }


# main

free=$(df -mP $mountpoint | grep $mountpoint | { read dev blocks used avail perc mounted ; echo $perc; })
    [ $free ] || { echo >&2 wrong mountpoint name, type $NAME_ -h for help; exit 1; }
free=${free:0:${#free}-1 } 

if (( $free > $mb ));then

   echo $mountpoint is running low on space! ${free}% of disk is full. | mail -s "Disk space $HOSTNAME" sysadmin@royaltyshare.com
   exit

fi
