#!/bin/bash
#
# Original version: fargo@fargonet.org
# http://openskills.info/view/boxdetail.php?IDbox=304&boxtype=scripts#
#
# This script is intended to send the updated internet IP address to an email recpient (or more
# than one). It can be usefull if you have an Adsl or Cable connection with a dynamic IP address. Whenever
# your ISP changes you internet IP address, you will be notified with an email. 
# So you will always know where to point your DNS, ssh or whatever...
#
#
# Modified and Cleaned up by Daevid Vincent [daevid@daevid.com]
#
# I setup up an /etc/mail/aliases to point to my cellphone's SMS gateway
# this works because even though my server changed IPs, it's still on the internet and can happily send mail
# then i get an instant SMS text message to my cell phone. works like a charm.
#
# /etc/crontab entry:
# */15 * * * * root /usr/local/bin/ipTeller.sh > /dev/null
#
#################################### BEGININNING OF THE SCRIPT #############################################
# Creates two files named "$IPFILE" and "mailtext" containing something the first time you execute the script,
# or recreates the files should they be missing.

IPFILE="/etc/ipTeller_ipaddress"
MAILFILE='/etc/ipTeller_mailtext'

if [ ! -f "$IPFILE" ]; then
	echo "creating $IPFILE"
	echo first_time_usage > $IPFILE
fi

if [ ! -f "$MAILFILE" ]; then
	echo "creating $MAILFILE"
	echo first_time_usage > $MAILFILE
fi 

# Gets last known IP address from the file "$IPFILE"
lastip=`cat $IPFILE`
echo "last ip saved is: $lastip"

# Gets current IP address
# This points to ppp0, Change this accordingly to your inet configuration.
# I used grep and awk, but they could not work correctly on some systems other than RedHat 7.2.
# You could skip the usage of awk and would probably get something like this:
# "inet addr:xxx.xxx.xxx.xxx  Bcast:xxx.xxx.xxx.xxx  Mask:xxx.xxx.xxx.xxx" (with your real config)
ip=`ifconfig eth0 | grep inet| awk '{ print $2 }'| awk -F : '{ print $2 }'`
echo "current ip address is: $ip"

# Checks if IP address has changed
if [ $ip != $lastip ]; then
	date=`date +%D\ %r`
	
	# Writes new IP address (if it has changed) to file, and creates mail text.
	echo $ip > $IPFILE
	echo "Your (daevid.com) domain's IP address is now $ip as of $date" > $MAILFILE
	
	echo "IP changed so sending message..."
	# Sends updated IP address to recipients. Change it as you need.
	mail -s "New Server IP." page_daevid@daevid.com < $MAILFILE
	
	echo "logging the IP change to /var/log/ipTeller_ipchange.log"
	echo "$date -- IP CHANGED TO: $ip" >> /var/log/ipTeller_ipchange.log

# Otherwise, if you still have the same IP address (lucky you!!!), 
# it nicely exit with no action.
else
	exit 0;
fi

exit;
######################################### END OF THE SCRIPT ################################################

