#!/bin/sh -e

# Usage: guess <file> | -   } "-" is for stdin instead of file.
#  Attempt to guess MIME type of random file and then call metamail
#  to apply it. Use "file" with special magic file to return MIME type directly.
# $Id: guess,v 1.3 1998/04/02 02:24:38 lcs Exp $

## Use SIPB's file because sun/sgi platforms' are too incompatible, for starters
file="/afs/sipb.mit.edu/project/sipb/bin/file"

## Do you believe in magic?
magic="/mit/mime/share/magic"

## This invokes	 /usr/andrew/bin/metamail on stock Athena.
## There's also /mit/mime/bin/metamail ..?
metamail="metamail"
infile=$1
tmpfile=""
	      
# Turn stdin into a file for file(1) to seek around in it, and metamail.
if [ "$infile" = "-" ]; then
    tmpfile=/tmp/GF$$
    trap "test -f $tmpfile && rm -f $tmpfile" 0 1 2 3 15
    cat > $tmpfile
    infile=$tmpfile
fi

# get best guess at contenttype:
contenttype=`$file -m $magic $infile | \
 awk '$1 == "'${infile}':" && NF == 2 { print $2 }'`

##DEBUG##
##echo 'guess: content="'$contenttype'"'

if [ -n "$contenttype" -a "$contenttype" != "data" ]; then
    $metamail -b -d -c "$contenttype" $infile
else
    echo "Cannot guess the true content-type of unidentified message content, skipping it."
fi

test -n "$tmpfile" && rm -f $tmpfile
