#! /bin/sh
# #############################################################################

       NAME_="lowswap"
       HTML_="monitor swap memory"
    PURPOSE_="notify when free swap memory is less then n Megabytes"
   SYNOPSIS_="$NAME_ [-hl] <n>"
   REQUIRES_="standard GNU commands, xmessage"
    VERSION_="1.3"
       DATE_="1999-08-10; last update: 2004-09-20"
     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:
     <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; 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

