:
##########################################################################
# Shellscript: findhomepage - check all URLs returned by "guesshomepage" 
# Author     :	Heiner Steven <heiner.steven@odn.de>
# Date       :	2000-09-02
# Requires   :	guesshomepage, geturl
# Category   :	WWW
# SCCS-Id.   :	@(#) findhomepage	1.3 03/06/03
##########################################################################
# Description
#	Uses "guesshomepage" to guess the home page of a person
#	given his e-mail address
##########################################################################

PN=`basename "$0"`			# Program name
VER='1.3'

Usage () {
    echo >&2 "$PN - find home page, $VER
usage: [-av] $PN e-mail [e-mail ...]
   -a:	try all home page names (instead of stopping after the first found)
   -v:	verbose output: print the names of the tried URLs"
    exit 1
}

Msg () {
    for MsgLine
    do echo "$PN: $MsgLine" >&2
    done
}

Fatal () { Msg "$@"; exit 1; }

# echon - echo, no newline

echon () {
    if [ X"$ECHON" = X ]
    then
	# Determine how to "echo" without newline: "echo -n" or "echo ...\c"
	if [ X`echo -n` = X-n ]
	then ECHON=echo; NNL="\c"
	else ECHON="echo -n"; NNL=""
	fi

    fi
    $ECHON "$*$NNL"
}

set -- `getopt ahv "$@"`
[ $# -lt 1 ] && Usage			# "getopt" detected an error

CheckAll=no
Verbose=no
while [ $# -gt 0 ]
do
    case "$1" in
	-a)	CheckAll=yes;;
	-v)	Verbose=yes;;
	--)	shift; break;;
	-h)	Usage;;
	-*)	Usage;;
	*)	break;;			# First file name
    esac
    shift
done

httpheader=${TMPDIR:=/tmp}/fh$$
trap 'rm -f "$httpheader"' 0
trap "exit 2" 1 2 3 13 15

for email
do
    for page in `guesshomepage "$email"`
    do
	geturl -h "$page" > "$httpheader" 2>/dev/null
    	if [ -s "$httpheader" ]
	then
	    [ $Verbose = yes ] && echon >&2 "trying $page... "
	    [ $Verbose = yes ] && head -1 "$httpheader" | cut -d' ' -f2-

	    # Analyze the HTTP header
	    # Example status: "HTTP/1.1 200 OK"
	    status=`awk 'NR==1 {print $2}' "$httpheader"`
	    case "$status" in
		2*)			# Page found!
		    url="$page"
		    ;;
		3*)			# Page moved
		    [ $Verbose = yes ] && echo >&2 "redirected!"
		    url=`awk '$1 == "Location:" {print $2}' "$httpheader"`
		    ;;
		*) ;;
	    esac
	    if [ -n "$url" ]
	    then
		echo "$url"
		[ $CheckAll = yes ] || break 2
		url=
	    fi
	else
	    [ $Verbose = yes ] && echo >&2 "trying $page... no"
	fi
    done
done
