#! /bin/bash

# A script to see if the server responds
# and on an error, will raise the alarm
# via Mail/SMS/Cityruf  Cityruf is similar to 2sms.com

WDIR=/usr/local/shellscripts/lm-livecheck

for i in `ls $WDIR/etc/`; do

  ## extract IP and fqdn from file name
  IP=`echo $i|cut -f1 -d"_"`;
  NAME=`echo $i|cut -f2 -d"_"`;

  ## ping host to see if it's up
  PING=$(/bin/ping -c2 -q -w2 $IP|grep transmitted|cut -f3 -d","|cut -f1 -d","|cut -f 1 -d"%")
  if [ $PING -eq " 0" ]; then
    ## Host is up
    echo "Server $IP ($NAME): ping OK";

    ## check if host was down and has now returned
    if [ -e $WDIR/deadhost/$IP ]; then
      echo "Server $IP ($NAME) came back to life";
      rm $WDIR/deadhost/$IP;
    fi

    ## now checking the ports
    for j in `cat $WDIR/etc/$i`; do

      RET=`/usr/bin/nmap -r --host_timeout 2500 --initial_rtt_timeout 2000 -p $j $IP|grep $j/tcp|cut -f1 -d"/"`;

      if [ -z $RET ]; then
        echo "$IP: Port $j is down";

        ## check if Port was down before
        if  [ -e $WDIR/deadports/$IP_$j ]; then
          echo "Port $j on server $IP ($NAME) is still dead";
        else
          echo "Port $j on server $IP ($NAME) has just died";
          touch $WDIR/deadports/$IP_$j;
          ## place commands for sending alarm here ##
        fi
      else
        echo "$IP: Port $j is up";
        ## check if port was down and has now been resurrected ##
        if  [ -e $WDIR/deadports/$IP_$j ]; then
          echo "Port $j on server $IP ($NAME) came back to life";
          rm $WDIR/deadports/$IP_$j;
        fi
      fi
    done

  else
    echo "Server $IP ($NAME): no response";

    ## check if Server has been dead before
    if [ -e $WDIR/deadhost/$IP ]; then
      echo "Server $IP ($NAME) is still dead.";
    else
      echo "Server $IP ($NAME) has just died.";
      touch $WDIR/deadhost/$IP;
      ## place commands for sending alarm here ##
    fi

  fi
done