#!/bin/bash

# A script to check for your LAN's current external IP4 address
# and to send an email to you at your web mail provider if a change has occurred.
#============================
# Depends on curl and mstmp which are available in the repositories
# Setting up mail using msmtp (edit  config file .msmtprc) has to be done beforehand
# Consider setting up a separate account for this and forwarding email to your regular address
# Run this script as root with limited permissions (say 0700)
# Returns the IP address and a message as to whether it has changed or not.

# based on code in http://tuxtweaks.com/2012/12/keeping-track-of-my-ip-address/;
# and http://stackoverflow.com/questions/13015206/verify-the-name-and-the-ip-address
#===========================

#Check to see if ip-address.log exists (this is where we keep track of the current address)
if [ -e /var/log/ip-address.log ]
then
   mv /var/log/ip-address.log /var/log/ip-address-old.log
fi

#Get my current IP address (behind firewall so have to go to an external site)

xc=1  # the return code
ip=''  # the ip address

until (( xc == 0 )) ; do

   #Spread the load among several sites that have been found to work reliably

   case $(( RANDOM  % 3 )) in

          0) ip=$(curl -s getip.tk);;
          1) ip=$(curl -s https://secure.informaction.com/ipecho/) ;;
          2) ip=$(curl -s http://icanhazip.com/) ;;

   esac
   xc=$? 
done

#Check that IP address is properly formatted

if echo "$ip" | egrep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' 
# It should consist of 4 numbers, separated by a '.'    .  

then
    #Check octets are within allowable range (0-255)

    validip="$(echo $ip | awk -F'.' '$1 <=255 && $2 <= 255 && $3 <= 255 && $4 <= 255')"     

      if [ -z "$validip" ]  # $validip is empty if the test above fails
      then
        echo "IP address octets are outside range"
        exit 0
      else                        # test above has passed
         #We have a valid address : update log file
          echo "$ip" > /var/log/ip-address.log
       fi
else
     echo “IP address failed format test” 
     exit 0
fi

#Check whether address has changed by comparing with the old log file if it exists

if [ -e /var/log/ip-address-old.log ]
then
   #Check files for difference. If the same then exit, otherwise send email.

   if diff /var/log/ip-address-old.log /var/log/ip-address.log > /dev/null
   then
      #They are the same, exit

      echo "No change in IP address"
      #exit 0
   else   #They are different, print message and send mail

      echo "IP address has changed... $ip"
      echo -e "IP address has changed... $ip" | msmtp --debug --from=default -t yourname@gmail.com
   fi
fi

# optionally send a mail anyway if any argument provided

if [[ "$1" == 'send' ]] 
then
     echo -e "IP address  is... $ip" | msmtp --debug --from=default -t norman.a.bakker@gmail.com
fi
