#!/bin/bash
# Filename: get_public_ip.txt
# Function: Get Public IP Address
# Author: shuhui

API_URL="http://myip.ipip.net"
FILE=/tmp/public_ip_gzwd.txt
LAST_FILE=/tmp/last_public_ip_gzwd.txt
FTP_HOST="pro.vqiu.cn"
FTP_PORT=2121
FTP_USER=username
FTP_PASS='password'

# Get Public IP From API
curl -B -s ${API_URL} | awk '{print $2}' | cut -b 6- >${FILE} 2>/dev/null

if [[ ! -e ${LAST_FILE} || "`cat ${FILE}`" != "`cat ${LAST_FILE}`" ]]
then
    # Delte the file from ftp server
    curl -s ftp://${FTP_USER}:"${FTP_PASS}"@${FTP_HOST}:${FTP_PORT}/ -X "DELE ${FILE##*/}"

    # Upload to ftp Server
    curl -s ftp://${FTP_USER}:"${FTP_PASS}"@${FTP_HOST}:${FTP_PORT}/ -T ${FILE}

    if [[ $? -eq 0 ]]
    then
        logger -t 'crond' 'Public IP address update successful.'
    fi

    # Rename
    \mv ${FILE} ${LAST_FILE}

else
    logger -t 'crond' 'Public IP address not changed.'
fi
