#!/usr/bin/env bash
# This script should only generate an email when the WAN IP has changed.
# run in launchd

my_email="andy.fragen@gmail.com"
# my_app=( "telekinesis - https://" "macpractice - " )
# my_app_port=( ":5010" ":3306" )
my_app=( "vnc://" )
my_app_port=( ":5900" )
debug=false

my_ip=`curl -s http://checkip.dyndns.org | awk '{print $6}' | awk ' BEGIN { FS = "<" } { print $1 } '`

if [[ -s /tmp/prevIP.txt ]]; then
  prevIP=$(cat /tmp/prevIP.txt)
else 
  echo "initialize" > /tmp/prevIP.txt
  prevIP=$(cat /tmp/prevIP.txt)
fi

if [[ $my_ip != $prevIP ]]; then
  echo $my_ip > /tmp/prevIP.txt
  echo "Prevous IP --> Current IP" > /tmp/currentIPInfo.txt
  my_change=`echo $prevIP "-->" $my_ip`
  echo $my_change >> /tmp/currentIPInfo.txt
  echo >> /tmp/currentIPInfo.txt
  for (( i = 0; i < ${#my_app[@]}; i++ )); do
    url_info="${my_app[$i]}$my_ip${my_app_port[$i]}\n"
    echo -e "$url_info" >> /tmp/currentIPInfo.txt
  done
  mail -E -s My_ip_address $my_email < /tmp/currentIPInfo.txt
fi

if [[ $debug == true ]]; then
  echo "===="
  echo `cat /tmp/currentIPInfo.txt`
  echo "===="
  rm /tmp/prevIP.txt
  rm /tmp/currentIPInfo.txt
fi


