#!/bin/sh 

# Galaxy turn mailer
# sends each <file>.r file to the name found in 
# the races:players file
# races:players file format
# racename:e-mail [e-mail2 [email3...]]
# racename must be correct casewise

# Needs expr, which on a sun is in /usr/5bin
# Assumes that each game is in a different directory (again, can be
# hacked around)

# Assumes that reports are in $cwd

#  $Header: /plaid/homes/zeus/Blind-2.47/support/RCS/mailer,v 2.47 1998/04/15 21:40:13 zeus Exp zeus $
#
#  $Log: mailer,v $
#  Revision 2.47  1998/04/15 21:40:13  zeus
#  *** empty log message ***
#
#

version=1.02
gm='bampton@cs.utk.edu'
gameaddr='zeus@cs.utk.edu'
fromhost=`hostname`

echo -n "Turn?"
read turn
turn2=`expr $turn + 1`

if [ -r .game-name ] ; then
  game=`cat .game-name`
else
  exit 1
fi

NOTICEDIR=notices
BULLETIN=$NOTICEDIR/global.bulletin
GAMEBUL=$NOTICEDIR/$game.info
TURNNOTICE=$NOTICEDIR/$game.$turn.notice

tmp=/tmp/galaxy.$$.send
rm -f $tmp
touch $tmp

if [ -r $BULLETIN ] ; then
   echo ""  >> $tmp
   echo "General Bulletins:" >> $tmp
   echo ""  >> $tmp
   cat $BULLETIN >> $tmp
   echo ""  >> $tmp
fi
if [ -r $GAMEBUL ] ; then
   echo "" >> $tmp
   echo "Bulletins for Galaxy Game $game">> $tmp
   echo "" >> $tmp
   cat $GAMEBUL >> $tmp
   echo ""  >> $tmp
fi
if [ -r $TURNNOTICE ] ; then
   echo "" >> $tmp
   echo "Bulletins for Galaxy Game $game Turn $turn">> $tmp
   echo ""  >> $tmp
   cat $TURNNOTICE >> $tmp
   echo ""  >> $tmp
fi

$PAGER $tmp

echo -n "^C to stop and fix..."
read junk


for file2 in  *.r ; do
  file=`basename $file2 .r`
  file=`echo $file`
  egrep '^'$file':' races:players > /dev/null
  if [ $? = 1 ] ; then
   echo "Player not found: $file"
  else
    use=`grep '^'$file':' races:players | awk -F: '{print $2}'`
    echo "Mailing $file Turn $turn to $use"

echo HELO $hostname >> /tmp/mailer.$$
    cat > /tmp/mailer.$$ << EOF
ONEX
EOF
echo "MAIL FROM:<$gameaddr>" >> /tmp/mailer.$$
for x in $use ; do 
  echo RCPT TO: "<$x>" >> /tmp/mailer.$$
  echo $x > /tmp/mailer.user.$$ # Yes > not >>
done
echo "DATA" >> /tmp/mailer.$$
echo To: \"`basename $file .r`\" "<"`cat /tmp/mailer.user.$$`">" >> \
       /tmp/mailer.$$
echo "From: Blind Galaxy Server <$gameaddr>" >> /tmp/mailer.$$
echo "Subject: $game Turn $turn for $file" >> /tmp/mailer.$$
echo "X-blind-mailer-version: $version" >> /tmp/mailer.$$
echo "X-Blind-gm: $gm" >> /tmp/mailer.$$
echo "X-orders-subject: $game orders for $file turn $turn2" >> /tmp/mailer.$$
if [ -r .game-time ] ; then
  echo -n "X-orders-time: " >> /tmp/mailer.$$
  cat .game-time >> /tmp/mailer.$$
fi
echo "" >> /tmp/mailer.$$
cat $tmp $file2 >> /tmp/mailer.$$
cat >> /tmp/mailer.$$ << EOF
.
quit
EOF

    /usr/lib/sendmail -bs < /tmp/mailer.$$ > /dev/null

    rm /tmp/mailer.$$ /tmp/mailer.user.$$
    sleep 10
  fi
done

rm $tmp
