#!/bin/sh
#
# simple mail-to-fax utility designed to replace HylaFAX's faxmail
# uses shell, sendfax, metamail, and uudecode
#
# - Lee Howard
#

#
# Mail addresses can be three ways:
#	1) user@host.org
#	2) "User Name" <user@host.org>
#	3) user@host.org (User Name)
#
# in the latter cases, quotes may or may not be used,
# there may or may not be any User Name at all, and User Name
# may come before or after user@host.org.
#
# We need to make sure we handle all these possibilities for
# both TO and FROM situations.  Return-Path is different.
#

RANDOMFAX=/tmp/faxtmp.$RANDOM

export METAMAIL_TMPDIR=$RANDOMFAX
if [ ! -d $METAMAIL_TMPDIR ]; then
	mkdir $METAMAIL_TMPDIR;
fi
rm -f $METAMAIL_TMPDIR/*

#
# metamail doesn't understand "multipart/alternative"
#

sed 's/multipart\/alternative/multipart\/mixed/' > $RANDOMFAX/_message_

TOLINE=`grep -e "^to:" -i $RANDOMFAX/_message_ | sed q`
FROMLINE=`grep -e "^from:" -i $RANDOMFAX/_message_ | sed q`
SUBJECT=`grep -e "^subject:" -i $RANDOMFAX/_message_ | sed q | sed -e 's/^[Ss]ubject:[ ]*//g'`

if [ "`echo $TOLINE | grep '<.*>'`" != "" ]; then
	TONUMBER=`echo $TOLINE| sed -e 's/.*<\(.*@[^\.]*\).*>.*/\1/'`
else
	TONUMBER=`echo $TOLINE| sed -e 's/^[Tt]o://g' -e 's/[ ]*\(.*@[^\.]*\).*/\1/'`
fi

FROMPATH=`echo $FROMLINE | sed -e 's/^[Ff]rom:[ ]*//g' -e 's/"//g'`

metamail -w -x $RANDOMFAX/_message_ > /dev/null 2>&1

# We also have to use uudecode, because metamail will only
# help us with mail that has Content-Type headers, although
# uudecode can only handle one attachment.  (Can a
# multi-attachment mail not have Content-Type headers?)

uudecode -o $METAMAIL_TMPDIR/_uudecoded_message_ $RANDOMFAX/_message_ > /dev/null 2>&1

rm -f $RANDOMFAX/_message_

if [ "$SUBJECT" != "" ]; then
	sendfax -R -f "$FROMPATH" -r "$SUBJECT" -d "$TONUMBER" $METAMAIL_TMPDIR/*
else
	sendfax -R -f "$FROMPATH" -n -d "$TONUMBER" $METAMAIL_TMPDIR/*
fi

rm -rf $RANDOMFAX
