#!/bin/sh

# fetch a list of "empty" mail messages for whitelisting
# This script should be run at most once a day

# The fetched file can be included in whiteclnt files.
#   By default it fetches http://www.iecc.com/dcc-testmsg-whitelist.txt



# Rhyolite Software DCC 1.3.66-1.21 $Revision$
# Generated automatically from fetch-testmsg-whitelist.in by configure.

exec </dev/null

DCC_HOMEDIR=/etc/dcc
URL=http://www.iecc.com/dcc-testmsg-whitelist.txt
TGT=testmsg-whitelist
PGM=ftp

USAGE="`basename $0`: [-x] [-h homedir] [-p fetch-pgm] [-s src-URL]"
while getopts "xh:p:s:" c; do
    case $c in
	x) set -x;;
	h) DCC_HOMEDIR="$OPTARG";;
	p) PGM="$OPTARG";;
	s) URL="$OPTARG";;
	*) echo 1>&2 "$USAGE"; exit 1;;
    esac
done
shift `expr $OPTIND - 1 || true`
if test "$#" -ne 0; then
    echo 1>&2 "$USAGE"
    exit 1
fi


FNAME=`expr "$URL" : '.*/\([^/][^/]*\)'`
if test -z "$FNAME"; then
    FNAME="$URL"
    if test -z "$FNAME"; then
	echo 1>&2 "source file not specified"
	exit 1
    fi
fi
LOG="$TGT.log"

cd $DCC_HOMEDIR

# don't bother if the file exists and is not at least 2 weeks old
if test -f "$TGT"; then
    if test "`find $TGT -mtime -14 -type f`"; then
	date "+%n%x %X: $TGT is too recent to fetch again" >> $LOG
	exit 0
    fi
fi

# use fetch, wget, curl, or ftp that understands URLs
rm -f $FNAME
PGM_B=`basename $PGM`
if test "$PGM_B" = wget; then
    PGM_B=
    $PGM -nd --retr-symlinks --recursive --no-host-directories \
	--passive-ftp  $URL >$LOG 2>&1
    if test -s $FNAME							\
		-a -n "`sed -n -e 2q					\
		    -e 's/.*DOCTYPE.*/HTML/p'				\
		    -e 's/<HEAD>/HTML/p' -e 's/<head>/HTML/p' $FNAME`"; then
	rm $FNAME
    fi
fi

if test "$PGM_B" = fetch; then
    PGM_B=
    HTTP_REFERER=DCC-script; export HTTP_REFERER
    $PGM -p -q -m $URL >$LOG 2>&1
fi

if test "$PGM_B" = curl; then
    PGM_B=
    $PGM -s -S --connect-timeout 30 --max-time 600 \
	 $URL -o $FNAME >$LOG 2>&1
    # --fail does not work on at least some versions of curl
    if test -s $FNAME							\
		-a -n "`sed -n -e 2q					\
		    -e 's/.*DOCTYPE.*/HTML/p'				\
		    -e 's/<HEAD>/HTML/p' -e 's/<head>/HTML/p' $FNAME`"; then
	rm $FNAME
    fi
fi

if test "$PGM_B" = ftp; then
    PGM_B=
    $PGM -p $URL  >$LOG 2>&1
    # if that did not work, try ancient anonymous FTP
    if test ! -s $FNAME; then
	HOST=`expr "$URL" : "ftp://\([^/]*\)/"`
	RFILE=`expr "$URL" : "ftp://[^/]*/\(.*\)"`
	echo "try old anonymous FTP"
	(echo "user anonymous `hostname`"; echo "get $RFILE $FNAME")	\
	    | ftp -n $HOST
    fi
    # some versions of ftp like to leave empty files
    if test ! -s $FNAME; then
	rm -f $FNAME
    fi
fi
# if some other program was specified, use it and hope it is simple enough
if test -n "$PGM_B"; then
    $PGM $URL
fi

if test ! -s "$FNAME"; then
    echo 1>&2 "failed to fetch $FNAME with $PGM"
    exit 1
fi
touch $FNAME		# work around wget timestamping

if test "$FNAME" != "$TGT"; then
    mv -f "$FNAME" "$TGT"
fi

date "+%n%x %X: fetched $TGT" >> $LOG
