#!/bin/csh -f
# 

if ($#argv <4) then
    echo "Usage: showexternal access-type name body-file [site [directory [mode]]]"
    exit -1
endif
set bodyfile=$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 ctype=`grep -i content-type: $bodyfile | sed -e 's/............: //'`
set cenc=`grep -i content-transfer-encoding: $bodyfile | sed -e 's/.........................: //'`
set username=""
set pass=""
set TMPDIR=/tmp/XXXternal.$$
mkdir $TMPDIR
cd $TMPDIR
set NEWNAME="mm.ext.$$"
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 $NEWNAME
quit
!
	if (! -e $NEWNAME) 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
    	set NEWNAME=$name
	breaksw
    case mail-server:  # A very special case
	if ("$bodyfile" == "") then
	    echo mail-server access-type requires a body file
	    exit -1
	endif
	echo Subject: Automated Mail server request > $NEWNAME
	echo To: ${name}@${site} >> $NEWNAME
	echo "" >> $NEWNAME
	cat $bodyfile >> $NEWNAME
	/usr/lib/sendmail -t  < $NEWNAME
	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
if ($cenc == base64) then
	mmencode -u -b < $NEWNAME > OUT
	mv OUT $NEWNAME
else if ($cenc == quoted-printable) then
	mmencode -u -q < $NEWNAME > OUT
	mv OUT $NEWNAME
endif

metamail -b -c $ctype $NEWNAME

if ($status) then
	echo metamail failed
	rm -rf $TMPDIR
	exit -1
endif

if ($NEWNAME != $name) then
	echo The data just displayed is stored in the file $TMPDIR/$NEWNAME
	echo "Do you want to delete it?"
	rm -i $NEWNAME
endif
if (! -e $NEWNAME) then
    rmdir $TMPDIR
endif
exit 0
