#!/bin/bash

# -----------------------------
# Glossary
# Local machine: the machine in which this script is running.
# Remote machine: the machine whose /etc/hosts file will be updated.
# -----------------------------
# This script is useful if you need to reach the local machine, and it has a
# dynamic ip.
# Run the script in background on the local machine. It will keep the remote
# /etc/hosts file up to date, and you will be able to reach the local
# machine from the remote machine using the name specified in the
# $myname variable. The script can run in both
# machines. Each one will keep the other's hosts file up to date.
#
# This script needs curl, ssh and sed. On the remote machine sshd must be
# running, with the ssh public key of the local machine in
# /root/.ssh/authorized_keys.

# Replace the values of these variables according to your needs.
seconds_btw_updates=120
ipchecker=https://secure.informaction.com/ipecho/
myname=local.machine.with.dynamic.ip
remotehost=needs.hosts.updates
remotelog=/var/log/messages

while true
do
    # Discover current ip address
    myip=`curl -s $ipchecker`

    # Delete the older record from the remote hosts file
    ssh root@$remotehost "sed -i '/$myname/d' /etc/hosts"

    # Insert a new record into /etc/hosts
    ssh root@$remotehost "echo $myip $myname >> /etc/hosts"

    # Update the remote log
    ssh root@$remotehost \
    "echo `date --rfc-3339=seconds`' $myname ip address updated' >> $remotelog"

    # Wait the desired period
    sleep $seconds_btw_updates
done
