#!/bin/sh
#
# outmail - send all files in /var/spool/out.going
# by Robert R Schneck
#
# This program sends all the messages in directory /var/spool/out.going
# using ssmtp -t.  
#
# It leaves a copy of each in the file /var/spool/gone.out
#
# It exits 0 if all messages were sent, 1 if any failed,
# and 2 if you tried to run this script twice simutaneously.
# The locking mechanism to check for that is completely ad hoc;
# trust it at your own risk.
#
# I like to have the mailhub set the Message-ID: header; you
# can uncomment the line with "killmsgid" below (and comment
# the following line) in order to strip any Message-ID: headers
# from the outgoing mail.  Make sure the killmsgid script is
# somewhere in your PATH.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
stat=0
if test -e /var/spool/out.going.lock
then
  echo 'outmail: Remove lock file /var/spool/out.going.lock first!'
  exit 2
fi
echo $$ >> /var/spool/out.going.lock
if test `cat /var/spool/out.going.lock` != $$
then
  echo 'outmail: Remove lock file /var/spool/out.going.lock first!'
  exit 2
fi
for name in /var/spool/out.going/*
do
  if test -e $name
  then
    stat=1
    echo "outmail: Attempting $name..."
#    if killmsgid $name | /usr/sbin/ssmtp -t
    if /usr/sbin/ssmtp -t < $name
    then echo "outmail: Succeeded."
	 echo "From outmail  "`date '+%a %b %d %H:%M:%S %Y'` >> /var/spool/gone.out
         cat $name >> /var/spool/gone.out
         echo >> /var/spool/gone.out
         /bin/rm $name
    else echo "outmail: Failure!!!"
    fi
  fi
done
if test $stat -eq 0
then
  echo "outmail: No outgoing mail."
fi
stat=0
for name in /var/spool/out.going/*
do
  if test -e $name
  then
    echo "outmail: Failed to send $name!"
    stat=1
  fi
done
/bin/rm /var/spool/out.going.lock
echo "outmail: Done."
exit $stat
