#!/bin/sh
# A basic script to update DynDNS address at DynDNS.org
# By John Piasetzki <john.piasetzki@gmail.com>

update_host() {
        LOCALIP=`curl -s http://checkip.dyndns.org | cut -d " " -f 6 | cut -d "<" -f 1`

        if [ "$LOCALIP" != "$LASTIP" ] ; then
                LASTIP="$LOCALIP"
                DRES=`curl -s -u $USER:$PASSWORD "https://members.dyndns.org/nic/update?hostname=$HOST&myip=$LOCALIP&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG"`
        fi
}

start_daemon() {
        logger -t dyndns "Starting dyndns sync"

        while true; do
                update_host
                logger -t dyndns "IP Update of $HOST returned $DRES"
                sleep 600
        done
}

show_help() {
        printf "usage: dyndns [-D] -u username -p password hosts\n"
        exit ${1}
}

check_parameters() {
        if [ -z "$USER" ]; then
                echo "dyndns: missing username"
                show_help 1
        fi

        if [ -z "$PASSWORD" ]; then
                echo "dyndns: missing password"
                show_help 1
        fi

        if [ -z "$HOST" ]; then
                echo "dyndns: missing host"
                echo $HOST
                show_help 1
        fi
}

while getopts 'u:p:hD' arg; do
        case "${arg}" in
                D) dflag=1;;
                u) USER="${OPTARG}" ;;
                p) PASSWORD="${OPTARG}" ;;
                h) show_help 1 ;;
                *) printf "dyndns: illegal option -- %s\n" "${arg}"; show_help 1 ;;
        esac
done

shift $(($OPTIND - 1))
HOST=$1

check_parameters
if [ ! -z "$dflag" ]; then
        start_daemon &
else
        update_host
fi
