#!/bin/sh

#set -ex 
set -e

TARGET="irc.se.linux.org"
TARGET=`host $TARGET | tail -1 | awk '{print $4}'`
TO="info@azoff.homeip.net"
CC="pelle@teknikpark.se"
SUBJECT="empty"
ERROR=0
SLEEP=30

echo "TARGET: $TARGET"
echo "TO: $TO"
echo "CC: $CC"
echo "Started script..."

while true; do
	DATE=`date`
	PING=`/usr/bin/fping -t 500 $TARGET 2>&1 |/usr/bin/awk '{print $3}'`

	if [ "$PING" == "alive" ]; then
		if [ $ERROR == 1 ]; then
			SLEEP=30
			ERROR=0
			SUBJECT="[STATUS: uppe] $DATE"
		fi
	else
		if [ $ERROR == 0 ]; then
			SLEEP=2
			ERROR=1
			SUBJECT="[STATUS: nere] $DATE"
		fi
	fi


	if [ "$SUBJECT" != "empty" ]; then
		TEMP=`mktemp /tmp/ping.XXXXXX`

		# skapa mailet
		echo -e "$TARGET\n\n" >> $TEMP
		echo -e "$DATE\n\n" >> $TEMP	
		/usr/bin/mtr --report -n -c 1 $TARGET >> $TEMP
		
		# skriv till terminalen
		echo $SUBJECT
	
		# skicka iväg mailet
		/bin/cat $TEMP | /usr/bin/mail -s "$SUBJECT" -c $CC $TO

		# rensa
		/bin/rm -f $TEMP
		SUBJECT="empty"
	fi

	sleep $SLEEP
done

