#!/bin/csh -f
# 
# based on Nathaniel Borenstein's "showexternal" code
echo $*
if ($#argv <4) then
    echo "Usage: grabexternal newfile access-type name [site [directory [mode]]]"
    exit -1
endif
set newfile=$1
set atype=`echo $2 | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
set name=$3
if ($#argv > 3) then
    set site=$4
else 
    set site=""
endif
if ($#argv > 4) then
    set dir=$5
else
    set dir=""
endif
if ($#argv > 5) then
    set mode=$6
else
    set mode=""
endif
set username=""
set pass=""

switch ($atype)
    case anon-ftp:
	set username=anonymous
	set pass=`whoami`@`hostname`
	# DROP THROUGH
    case ftp:
	if ("$site" == "") then
	    echo -n "Site for ftp access: "
	    set site=$<
	endif
	if ("$username" == "") then
	    echo -n "User name at site ${site}: "
	    set username=$<
	endif
	if ("$pass" == "") then
	    echo -n "Password for user $username at site ${site}: "
	    stty -echo
	    set pass=$<
	    stty echo
	    echo ""
	endif
	if ("$dir" == "") then
	    set DIRCMD=""
	else
	    set DIRCMD="cd $dir"
	endif
	if ("$mode" == "") then
	    set MODECMD=""
	else
	    set MODECMD="type $mode"
	endif
	echo OBTAINING MESSAGE BODY USING FTP
	ftp -n <<!
open $site
user $username $pass
$DIRCMD
$MODECMD
get $name $newfile
quit
!
	if (! -e $newfile) then
	    echo FTP failed.
	    exit -1
	endif
	breaksw
    case afs:
    case local-file:
	if (! -e $name) then
	    echo local file not found
	    exit -1
	endif
    	cp $name $newfile
	breaksw
    case mail-server:  # A very special case DOESN'T WORK
	if ("$bodyfile" == "") then
	    echo mail-server access-type requires a body file
	    exit -1
	endif
	echo Subject: Automated Mail server request > $newfile
	echo To: ${name}@${site} >> $newfile
	echo "" >> $newfile
	cat $bodyfile >> $newfile
	/usr/lib/sendmail -t  < $newfile
	if ($status) then
	    echo sendmail failed
	    rm -rf $TMPDIR
	    exit -1
	endif
	rm -rf $TMPDIR
	echo Your $ctype data has been requested from a mail server.
	exit 0
    default:
	echo UNRECOGNIZED ACCESS-TYPE
	exit -1
endsw

exit 0
