#!/bin/sh
#
# TMON - Sms Warning script, released under the GPL license 
# http://www.gnu.org/licenses/gpl.html
#
# Version 0.4
#
# Author
# Daniele Duca (daniele[-at-]danieleduca.it)
#
# Changelog
# 20/01/2005 - First public release (0.4) 
# xx/11/2004 - Changed SMS gateway to Vola.it (private)
# xx/01/2003 - Bugfixes (private)
# xx/10/2002 - Initial release 0.1 (private)

# Vola.it username and password

VOLAUID="yourVolaUID"
VOLAPASS="yourVolaPASS"

# My masters

MASTERS[1]="Your Name"
MASTERS[2]="Your-mobile-number-with-prefix"
MASTERS[3]="Another Name"
MASTERS[4]="Another-mobile-number-with-prefix"

ST=$(date)
MCOUNT=${#MASTERS[@]}

SMSP="/usr/bin/curl http://sms.vola.it/cgi/volasms_gw.php?UID=$VOLAUID\&PWD=$VOLAPASS\&CMD=1\&DEST="

function warn() {
  if [ -f /tmp/mess ]; then
    echo "  Network is messed up"
    exit 1
  fi
  if [ ! -f /tmp/destroyed ]; then
    touch /tmp/destroyed
    echo "  Lagging warning.."
    rm /tmp/checking
    exit 1
  fi
  rm /tmp/destroyed
 
  declare -a array
  array=$*
  a=1
  while [ "$a" -le "$MCOUNT" ]
  do
       if [ `expr $a % 2` == "0" ]; then
         $SMSP${MASTERS[a]}\\\&MSG=$SMS
       else
         echo " /-Now warning ${MASTERS[a]}"

       fi
         a=$(($a+1))
  done
  /bin/touch /tmp/mess

}

function checkh() {
echo -n "  Port $2... "
tc=`telnet $1 $2 << FFFFFF 2>/dev/null | grep Connected`
if [ -z "$tc" ]; then
  echo "failed!"
  SMS="-TMON-%20Port%20$2%20on%20host%20$1%20doesn't%20replyed"
  warn "${MASTERS[*]}"
  return 1 
else
  echo "ok!"
  return 0
fi
}

function pinghost() {
echo "Now checking $1..."
echo -n "  Ping... "
if ping -w 18 -l 5 -n -c 2 "$1" &>/dev/null; then
  echo "ok!"
  return 0 
else
  echo "failed!"
  SMS="-TMON-%20Hi!%20Host%20$1%20doesn't%20replied%20to%20my%20ping"
  warn "${MASTERS[*]}"
  return 1
fi
sleep 5
}

function fullcheck() {
  e=2
  COUNT=${#host[@]}
  if pinghost ${host[1]} ; then
    while [ "$e" -le "$COUNT" ]
    do
      checkh ${host[1]} ${host[e]}
      e=$(($e+1))
    done
  else
    echo "It doesn't make sense to check services while the server is down"
  fi
  sleep 5
  unset host
}
if [ -f /tmp/checking ]; then
  echo "  Already checking."
  exit 0
else
  /bin/touch /tmp/checking
fi
if [ -f /tmp/mess ]; then
  echo "  Network is messed up."
  exit 1
fi

# Main - Add your hostnames here

echo "$ST - Starting TMON script"

pinghost some.host.name

host[1]="another.host.name"
host[2]="25"
host[3]="110"
fullcheck
 
host[1]="any.another.host.name"
host[2]="80"
fullcheck

rm -f /tmp/checking
rm -f /tmp/destroyed
ST=$(date)
echo "$ST - exiting..."
exit 0

