#! /bin/bash
# #############################################################################

       NAME_="lowswap"
    PURPOSE_="notify when free swap memory is less then n Megabytes"
   SYNOPSIS_="$NAME_ [-hl] <n>"
   REQUIRES_="standard GNU commands, xmessage"
    
# #############################################################################

usage () {

echo >&2 "$NAME_ - $PURPOSE_
Usage: $SYNOPSIS_
Requires: $REQUIRES_
Options:
     <n>, an integer referring to Mb
     -h, usage and options (this help)
     -l, see this script"
    exit 1
}

# enabling extended globbing
shopt -s extglob

# option handling
case $1 in
    -h) usage ;;
    -l) more $0; exit 1 ;;
    +([0-9])) # arg1 can only be an integer

        # check if required command is in $PATH variable
        which xmessage &> /dev/null
        [[ $? != 0 ]] && { echo >&2 the required \"xmessage\" command is not in your PATH variable; exit 1; }

    while :;do

        swap_free=$(free -mo | grep Swap | { read a b c d; echo $d; })

        if (( $swap_free < $1 ));then

            # display windowed message if x is running; ring a bell
            ps -aux | grep -q xinit
            if [ $? = 0 ];then
                xmessage -center Swap is running low! Less then ${1}Mb left.
                echo -en \\a
                exit 0
            else
                # write message to terminal and ring a bell
                echo -e \\a Swap is running low! Less then ${1}Mb left.
                exit 0
            fi

        fi

        sleep 60s # how often we check swap

    done ;;

    *) echo invalid argument, type $NAME_ -h for help ; exit 1 ;;

esac


