#!/bin/bash
#
# This software is released under the GNU General Public License (GPL)
# which can be found at http://www.gnu.org/licenses/gpl.txt.
# 
# Using this program is "at own risk", the author takes no responsibility
# for whatever trouble or harm this script may cause. (Shouldn't cause any,
# but you know how it is.)
#
# Copyright 2004 Anders K. Madsen <lillesvin@tiscali.dk>

# Exit codes:
#   0:  Success!
#   1:  Invalid argument or missing parameter.
#   2:  DYN_HOSTS does not exist.
#   4:  DYN_HOSTS is not readable.
#   8:  One or more hosts failed... :(

# Set some things.
VERSION="0.8"
AUTHOR="Anders K. Madsen <lillesvin@tiscali.dk>"

# Set DYN_HOSTS file to default (/etc/dyndns.hosts)
DYN_HOSTS="/etc/dyndns.hosts"

# Define some functions.
function write_help
{
    cat<<EOF
dyndnsupdate ${VERSION} by ${AUTHOR}
Usage:
    dyndnsupdate [options [args]]

    -f <file>       Use hosts and urls from this file instead of
                    the default. (/etc/dyndns.hosts)
    -s              Produce no output.
    -h              Print this help and exit.
EOF
    exit 0
}

function output
{
    if test ! $SILENT; then
        echo -en "${1}"
    fi
}

function test_file
{
    if test -f $DYN_HOSTS; then
        if ! `test -r $DYN_HOSTS`; then
            echo "dyndnsupdate: ${DYN_HOSTS} is not readable. (Permissions problem?)"
            exit 4
        fi
    else
        echo "dyndnsupdate: ${DYN_HOSTS} does not exists."
        exit 2
    fi
}

# Brief usage explanation.
USAGE="Usage: `basename $0` [-h|-s|-f <file>]"

# Implementing getopts.
while getopts "f:sh" OPT
do
    case "$OPT" in
        h)  write_help;;
        s)  SILENT=0;;
        f)  DYN_HOSTS=$OPTARG;;
        *)  echo $USAGE;exit 1;;
    esac
done

# Test DYN_HOSTS.
test_file

output "Updating dyndns domains (from file: ${DYN_HOSTS}):\n"

upd_hosts=(`egrep ^[^#] $DYN_HOSTS | awk {'print $1'}`)
upd_urls=(`egrep ^[^#] $DYN_HOSTS | awk {'print $2'}`)
ind=0
FAIL=0

while test ${ind} -lt ${#upd_urls[@]}; do
    
    output "\t${upd_hosts[${ind}]}: "
    suc=`lynx -mime_header "${upd_urls[${ind}]}" | head -1 | awk {'print $2'}`
    if test $suc -eq 200; then
        output "done\n"
    else
        output "failed\n"
        FAIL=`expr $FAIL + 1`
    fi

    ind=`expr $ind + 1`
done

# Did anything fail?
if test $FAIL -gt 0; then
    exit 8
else
    exit 0;
fi
