#!/bin/bash
PREVIP=$(cat /opt/utils/StoredIP)
MAILFILE="Tempfile2"
TRYCOUNT=10
while [ TRUE ]; do

  if [ $TRYCOUNT -le 0 ]; then
    echo Error occured.
    exit 1
  fi

  CURRENTIP=$(curl --silent http://checkip.dyndns.org/|grep -Eo '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}')
  STATUS=$?
  sleep 5
  if [ ! $STATUS ]; then
    let TRYCOUNT-=1
  elif [ ! "$CURRENTIP" ]; then
    let TRYCOUNT-=1
  else
    break
  fi

done

if [ "$PREVIP" = "$CURRENTIP" ]
then
  exit 0
fi

touch $MAILFILE
exec 6>&1
exec > $MAILFILE



echo This is an auto generated mail to notify the server IP had updated:
echo 這是一封自動發送的電郵,以通知服務器地址經已更新:
echo 
echo Server Address:
echo 服務器地址:
echo $CURRENTIP
echo 
echo 
echo Pleas do not reply to this email.
echo 請勿回覆。
echo If you have any questions, please feel free to contact tgckpg@gmail.com
echo 如有任何疑問,請電郵至tgckpg@gmail.com
echo 
echo Regards,
echo 祝 安康
echo Penguin 鵬兄
echo 
echo 

echo $CURRENTIP > /opt/utils/StoredIP

while read line
do mutt -s "通知Notice: 服務器地址已變更New address for server." -- $line < $MAILFILE
done < /opt/utils/mailList
rm $MAILFILE