#!/bin/sh
### Monitor free disk space
# Display alert if the free percentage of space is >= $ALERT

#
# Static Config Variables
#
# free space percentage to trigger an alert
ALERT=90

#
# Static Binary Paths
#
DF='/usr/bin/df'
GREP='/usr/bin/grep'
AWK='/usr/bin/awk'
CUT='/usr/bin/cut'
HOSTNAME='/usr/bin/hostnamectl hostname'
DATE='/usr/bin/date'
MSG_CLIENT='/usr/bin/lh_notify-send'

#
# Static System Variables
#
THIS_HOST=`${HOSTNAME}`

#
# Check CLI Options
#
VERBOSE=false
OSD=false
for ARG in "$@" ; do
        case $ARG in
        "-v")
                VERBOSE=true
                ;;
        "-osd")
                OSD=true
                ;;
        esac
done

[ $VERBOSE = true ] && echo "Checking free disk space on ${THIS_HOST}"
[ $VERBOSE = true ] && echo "Threshold for warning is ${ALERT}%"
[ $VERBOSE = true ] && echo "------------------------------------------------------------------"

# Dynamic Variables
#DATE_STR=`${DATE} "+%d-%B-%y @ %H%Mhrs"`

# Call df to find the used percentages. Grep for only local disks (not remote mounts like nfs or smb)
# Pipe the output to awk to get the needed columns, then start a while loop to process each line.
$DF -HPl | $GREP -E "^/dev/" | $AWK '{ print $5 " " $6 " " $1 }' | while read OUTPUT ; do
    USED_PCENT=$(echo ${OUTPUT} | $AWK '{ print $1}' | $CUT -d'%' -f1  )    # Used space as a percentage
    PARTITION=$(echo ${OUTPUT} | $AWK '{ print $2 }' )                      # Mount Point (eg, /home)
    DEVICE=$(echo ${OUTPUT} | $AWK '{ print $3 }' )                         # Device (eg, /dev/sda1 or LABEL or UUID)
    if [ $VERBOSE = true ] ; then
        echo -e "${USED_PCENT}% used:\tDevice ${DEVICE} mounted to ${PARTITION}"
    fi
    if [ ${USED_PCENT} -ge $ALERT ]; then
        echo "WARNING: Partition (${PARTITION}) on (${DEVICE}) is ${USED_PCENT}% full on ${THIS_HOST}"
        if [ $OSD = true ] && { [ ${PARTITION} = / ] || [ ${PARTITION} = /home ] || [ ${PARTITION} = /data/srv/mysql ]; } then
            $MSG_CLIENT --app-name="Disk Space WARNING" "Partition (${PARTITION}) on (${DEVICE}) is ${USED_PCENT}% full."
        fi
    fi
done

exit 0
