#!/bin/sh
#	BSDI	audiosend,v 1.3 1997/06/22 16:10:11 jch Exp
#
# Copyright (c) 1991 Bell Communications Research, Inc. (Bellcore)
# 
# Permission to use, copy, modify, and distribute this material 
# for any purpose and without fee is hereby granted, provided 
# that the above copyright notice and this permission notice 
# appear in all copies, and that the name of Bellcore not be 
# used in advertising or publicity pertaining to this 
# material without the specific, prior written permission 
# of an authorized representative of Bellcore.  BELLCORE 
# MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY 
# OF THIS MATERIAL FOR ANY PURPOSE.  IT IS PROVIDED "AS IS", 
# WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
#

unset IFS

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}
}

# Defaults
RECORD_AUDIO=${RECORD_AUDIO:-vrec}
PLAY_AUDIO=${PLAY_AUDIO:-vplay}
EDIT_AUDIO=${EDIT_AUDIO:-mxv}
METAMAIL_TMPDIR=${METAMAIL_TMPDIR:-${TMPDIR:-/tmp}}
SENDMAIL=/usr/sbin/sendmail

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}/audiosend.$$
mkdir -p -m 0700 "${tempdir}" || cleanup 1
TEMPDIR=${tempdir} ; unset tempdir
saved_PWD=${PWD}
cd ${TEMPDIR} || cleanup 1

if [ $# -ge 1 ]; then
    to="${1}"; shift
fi
while [ -z "${to}" ]; do
    read -p "To: " to
done

read -p "Cc: " cc

read -p "Subject: " subject

fname=${TEMPDIR}/audio-draft.$$
fnameraw=${TEMPDIR}/audio-raw.$$

echo "To: ${to}" > "${fname}"
if [ -n "${subject}" ]; then
    echo "Subject: ${subject}" >> "${fname}"
fi
if [ -n "${cc}" ]; then
    echo "Cc: ${cc}" >> "${fname}"
fi
echo "MIME-Version: 1.0" >> "${fname}"
echo "Content-Type: audio/basic" >> "${fname}"
echo "Content-Transfer-Encoding: base64" >> "${fname}"
echo  "" >> "${fname}"

if audiocompose audio/basic "${fnameraw}"; then
    mimencode -b < "${fnameraw}" >> "${fname}"
    rm -f "${fnameraw}"
    echo "" >> "${fname}"

    echo -n "Sending mail, please wait...  "
    if ${SENDMAIL} "${to}" "${cc}" < "${fname}"; then
	cleanup 0 "Done."
    else
	echo "Mail delivery failed, draft saved in ${fname}"
    fi
else
    # if we have something recorded then save the draft
    if [ -s "${fnameraw}" ]; then
	mimencode -b < "${fnameraw}" >> "${fname}"
	rm -f "${fnameraw}"
	echo "" >> "${fname}"
	echo "Draft saved in ${fname}"
	exit 1
    fi
    cleanup 1
fi
