#!/bin/sh
#
# mass mail a message (from a file) to adresses (from a file)

# defaults:

sourcedir=/export/massmail

recipfile=$sourcedir/recip.list
msgfile=$sourcedir/msg.text
statusfile=$sourcedir/zustand2
subject="testing mass mailing functions"
log=/var/log/massmail/massmail.log
returnadd=postmaster@`domainname`
admin=$USER
USAGE="massmail -s subject -r recipient-list -m message-file -a return-address"

# exit if statusfile zustand2 does not exist 

if [ ! -f $statusfile ]; then
  (
  echo "terminated due to statusfile <> zustand2 at `date`"
  echo
  ) | tee -a $log
  exit 0
fi

# prompt usage if no arguments are given

while [ $# -gt 0 ]
do
  case $1 in
  -s) subject=$2
      shift;;
  -r) recipfile=$2
      shift;;
  -m) msgfile=$2
      shift;;
  -a) returnadd=$2
      shift;;
  *)  echo $USAGE
      exit 1;;
  esac
  shift
done

sendmail=/usr/lib/sendmail
delay=1

if [ ! -f $recipfile ]; then
  echo "cannot find address list $recipfile"
mail=/usr/ucb/mail

  exit 1
fi
if [ ! -f $msgfile ]; then
  echo "cannot find email text $msgfile"
  exit 1
fi

# ok, now start creation of email
# set status file to zustand3

rm $sourcedir/zustand?
cp /dev/null $sourcedir/zustand3

# calculate time estimated

ndat=`wc -l $recipfile 2> /dev/null | awk '{print $1}'`
time=`echo "$ndat $delay" | awk '{printf("%.2f",($1*($2+1.88))/3600)}'`

(
echo "mass mail started at `date`"
echo
echo "subject line      : $subject"
echo "recipient list    : $recipfile"
echo "message file      : $msgfile"
echo "logfile           : $log"
echo "return address    : $returnadd"
echo "delay             : $delay second(s)"
echo "time required     : $time hour(s) for $ndat adresses"
echo
) | tee -a $log
sleep 3

j=0;
while read rec
do
  j=`expr $j + 1`
  echo "sending #$j to: $rec" | tee -a $log

  # dispatch aoutgoing parcel to addressee

  (
cat <<eof
From: $returnadd
Subject: $subject
Reply-To: $returnadd
To: $rec
eof

  cat $msgfile
  ) | $sendmail -f "$returnadd" $rec
  if [ $? != 0 ]; then
    echo "dispatch of #$j returned with non-zero exit status" | tee -a $log
  fi
  sleep $delay

done < $recipfile

# backup parameter files

backupdir=/var/log/massmail/`date +%Y%m%d%k%M%S`
mkdir $backupdir
cp $sourcedir/recip.list $backupdir
cp $sourcedir/msg.text $backupdir
rm $sourcedir/*.????
mv $sourcedir/zustand3 $sourcedir/zustand1

# print final message

(
echo
echo "backup directory is $backupdir"
echo "mass mail completed at `date`"
echo
) | tee -a $log

exit 0
  