#!/usr/local/bin/bash
#
# mail-announce - use voice synth to report incoming mail
#
# $Id: mail-announce,v 1.19 2008/12/30 15:59:24 esm Exp $
#

###############################################################################
# BEGIN user-customizable section

# Where we send esd output.
#
# This is declared as an array (-a), because you may have multiple
# places where you want sounds to go.  For instance, Ed has a Chumby
# (Google it) with esd installed, so sound goes to three places: his
# desktop system, his laptop, and the Chumby.
#
# Change the 12345 as needed.
declare -a servers
servers[0]='-s localhost:12345'

# END   user-customizable section
###############################################################################

# Script name.
ME=$(basename $0)

die() {
    echo "$@" >&2
    exit 1
}

# Prevent someone from running this at the command line & hanging forever
test -t 0 && die "$ME: please feed me an email message on stdin"

#
# Extract source address.  Perform (using Perl) some translations on addr.
#
# This basically converts  From: Your Friend Billy <billybob@somewhere.com>
#                     to   From: somewhere.com  billybob  Your Friend Billy
#
# ...which Ed finds easier to listen to.  If the TTS plays the address
# as-is, by the time you've started paying attention, all you hear is
# something like "blahblah.com" which isn't too helpful.  This way,
# you hear a real name as the last thing.
#
from=$(formail -X From: | sed -e 's/[\"\*<>\\]//g' -e 's/^From:\(.*\) \(.*\)@\(.*\)/From: \3: \2; ( ) \1/' | perl -MMIME::Words=:all -e '$x=scalar(decode_mimewords(<STDIN>)); $x =~ s/\[BAR\]//; print $x;')
#echo "from='$from'"
test -z "$from" && die "$ME: No 'From' address found"

# Generate a tmp file into which we copy the festival results
tmpfile=/tmp/$ME.tmp.$$.raw
rm -f $tmpfile

trap 'status=$?; rm -rf $tmpfile && exit $status' 0
trap 'exit $?' 1 2 13 15


# Invoke speech synthesizer to generate an 8KHz sound file...
festival <<EOF
(voice_rab_diphone)
(Parameter.set 'Audio_Command "ln \$FILE $tmpfile")
(Parameter.set 'Audio_Method  'Audio_Command)
(SayText "$from")
EOF

# ...and output the results.  Ignore the silly 'opening' nonsense from esdcat.
for server in "${servers[@]}"; do
    (esdcat -r 8000 $server $tmpfile 2>&1 |grep -v 'opening socket,') &
done

# Clean up... but wait a bit, in case the esdcat's haven't started yet
sleep 2
rm -f $tmpfile

exit 0
