#!/bin/sh

unset IFS

usage() {
    echo $0
    echo "Usage: $(basename ${0}) body-file access-type name [ site [ directory [ mode [ server ] ] ] ]" 1>&2
    exit 1 
}

cleanup() {
    if [ $# -gt 0 ]; then
    	rc=${1}; shift
    else
	rc=0
    fi
    if [ $# -gt 0 ]; then
	for line; do
	    echo "$(basename ${0}): ${line}"
	done
    fi
    if [ -n "${METAMAIL_TMPDIR}" -a -e "${METAMAIL_TMPDIR}" ]; then
	if [ -n "${TEMPDIR}" -a -e "${TEMPDIR}" ]; then
	    rm -rf "${TEMPDIR}"
	fi
    fi
    exit ${rc}
}

lower() {
    tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
}

keyword() {
    keyword=$(echo ${1} | lower)
    value=$(grep -i "${keyword}:" "${bodyfile}" | lower | sed -e "s/${keyword}: //")
    if [ $# -gt 1 -a -z "${value}" ]; then
	value=${2}
    fi
    echo "${value}"
}

yesorno() {
    while true; do
	read ${1:+"-p${1} (y/n) [y] ? "} ANS
	case ${ANS} in
	    n|no|N|NO)
		return 1;
		;;
	    y|yes|Y|YES|"")
		return 0;
		;;
	esac
    done
}

SENDMAIL=/usr/sbin/sendmail
METAMAIL_TMPDIR=${METAMAIL_TMPDIR:-${TMPDIR:-/tmp}}
FTP=${FTP:-ftp}

trap "cleanup 1 interrupted" 1 2 15

if [ $# -lt 3 -o $# -gt 7 ]; then
    usage
fi

bodyfile=${1}
atype=$(echo ${2} | lower)
name=${3}
site=${4}
dir=${5}
mode=${6}
server=${7}

ctype=$(keyword "content-type" "text/plain")
cenc=$(keyword "content-transfer-encoding")
username=
pass=

if [ ! -e "${METAMAIL_TMPDIR}" ]; then
    cleanup 1 "'${METAMAIL_TMPDIR}' does not exist"
elif [ ! -d "${METAMAIL_TMPDIR}" ]; then
    cleanup 1 "'${METAMAIL_TMPDIR}' is not a directory"
fi
tempdir=${METAMAIL_TMPDIR}/showexternal.$$
mkdir -m 0700 "${tempdir}" || cleanup 1
TEMPDIR=${tempdir} ; unset tempdir
saved_PWD=${PWD}
cd ${TEMPDIR} || cleanup 1

NEWNAME="mm.ext.$$"
NEEDSCONFIRMATION=1
case "${atype}" in
    "anon-ftp")
	(
	    echo "This mail message contains a POINTER (reference)"
	    echo "to data that is not included in the message itself."
	    echo "Rather, the data can be retrieved automatically using"
	    echo "anonymous FTP to a site on the network."
	) | fmt
	;;
    "ftp")
	(
	    echo "This mail message contains a POINTER (reference) to data"
	    echo "that is not included in the message itself.  Rather, the"
	    echo "data can be retrieved automatically using the FTP protocol"
	    echo "to a site on the network."
	) | fmt    
	;;
    "mail-server")
	if [ -z "${server}" ]; then
	    # Backward compatibility with some broken stuff
	    server="${name}@${site}"
	    echo "WARNING -- old style mailserver syntax, using server ${server}"
	fi
	(
	    (
		echo "This mail message contains a POINTER (reference) to"
		echo "data that is not included in the message itself.  Rather,"
		echo "the data can be retrieved by sending a special mail message"
		echo "to a mail server on the network.  However, doing this"
		echo "automatically is slightly dangerous, because someone might"
		echo "be using this mechanism to cause YOU to send obnoxious mail."
		echo "For that reason, the mail message that WOULD be sent is"
		echo "being shown to you first for your approval."
		echo ""
		echo "This is the message that will be sent if you choose to go"
		echo "ahead and retreive the external data:"
	    ) | fmt
	    ( 
		echo ""
		echo "Subject: Automated Mail Server Request"
		echo "To: ${server}"
		echo ""
		sed -e 1,/^\$/d "${bodyfile}"
	    ) 
	) | ${METAMAIL_PAGER:-more}
	;;

    *)
	# IGNORE ALL THE OTHERS -- AUTOMATIC FOR LOCAL-FILE, AFS.
	NEEDSCONFIRMATION=0
	;;
esac

if [ ${NEEDSCONFIRMATION} -eq 1 ]; then
    echo ""
    yesorno "Do you want to proceed with retrieving the external data" || cleanup 0
fi

case "${atype}" in
    "anon-ftp"|"ftp")
    	if [ "${atype}" = "anon-ftp" ]; then
		username=anonymous
		pass="$(whoami)@$(hostname)"
	fi
	if [ -z "${site}" ]; then
	    read -p "Site for ftp access: " site
	fi
	while [ -z "${username}" ]; do
	    read -p "User name at site ${site}: " username
	done
	if [ -z "${pass}" ]; then
	    stty -echo
	    read -p "Password for user ${username} at site ${site}: " pass
	    stty echo
	    echo ""
	fi
	echo "OBTAINING MESSAGE BODY USING FTP"
	echo "SITE: ${site} USER ${username}"
	(
	    echo "open \"${site}\""
	    echo "user \"${username}\" \"${pass}\""
	    if [ -n "${dir}" ]; then
		echo "cd \"${dir}\""
	    fi
	    if [ -n "${mode}" ]; then
		echo "type ${mode}"
	    fi
	    echo "get \"${name}\" \"${NEWNAME}\""
	    echo "quit"
	) | ${FTP} -n
	if [ ! -e "${NEWNAME}" ]; then
	    cleanup 1 "FTP failed."
	fi
	;;
    "afs"|"local-file")
	if [ ! -e "${name}" ]; then
	    cleanup 1 "local file not found"
	fi
    	NEWNAME=${name}
	echo "GETTING BODY FROM FILE NAMED: '${NEWNAME}'"
	;;
    "mail-server")  # A very special case
	if [ -z "${bodyfile}" ]; then
	    cleanup 1 "mail-server access-type requires a body file"
	fi
	(
	    echo "Subject: Automated Mail Server Request"
	    echo "To: ${server}"
	    echo ""
	    sed -e 1,/^\$/d "${bodyfile}"
	    echo ""
	) | ${SENDMAIL} -t || cleanup 1 "sendmail failed"
	cleanup 0 "Your ${ctype} data has been requested from ${server}."
	;;
	
    *)
	cleanup 1 "UNRECOGNIZED ACCESS-TYPE: '${atype}'"
	;;
esac

case "${cenc}" in
    "base64")
	mimencode -u -b < "${NEWNAME}" > OUT && mv OUT "${NEWNAME}"
	;;
    "quoted-printable")
	mimencode -u -q < "${NEWNAME}" > OUT && mv OUT "${NEWNAME}"
	;;
    "")
	;;
    *)
	echo "UNRECOGNIZED CONTENT-TRANSFER-ENCODING: '${cenc}'"
	;;
esac

cd "${saved_PWD}" ; unset saved_PWD

if [ "${atype}" = "local-file" ]; then
    metamail -p  -b -c "${ctype}" "${NEWNAME}"
else
    metamail -p -b -c "${ctype}" "${TEMPDIR}/${NEWNAME}"
fi

if [ $? -ne 0 ]; then
    cleanup 1 "metamail failed"
fi

if [ "${NEWNAME}" != "${name}" ]; then
	echo ""
	echo "The data just displayed is stored in the file '${TEMPDIR}/${NEWNAME}'"
	yesorno "Do you want to delete it" && rm "${TEMPDIR}/${NEWNAME}"
fi

if [ ! -e "${TEMPDIR}/${NEWNAME}" ]; then
    rm -rf "${TEMPDIR}"
fi
exit 0
