#!/bin/csh -f

# Inspects $1.txt (ignoring any extension in $1) and:

# (1) Makes a list of student grade records (on $1.post) to be posted
# for all those students that have a secret code in the "POST" column

# (2) Makes a file for each student who has "EMAIL" in his "POST"
# column and doesn't have "NOBODY" under "EADDR".  Each file name of
# the form eaddr.egr, where "eaddr" is the students email address.
# The file contains a message taken from $1msg.txt and then the
# student's complete record from the spreadsheet (excepting the POST,
# CLS, and NUMBER column entries).

# (3) Does the same thing as in (2) but for "FAX" rather than "EMAIL"
# entries under "POST".  Here, the file names are of the form
# info@telnum.fgr, where "info" is the name and perhaps location
# information (with spaces converted to underscores), and "telnum" is
# the fax telephone number.

# You can follow up with the "emailgrades" and "faxgrades" commands to
# send the grade records to the students.

umask 066

set tmpmail = /tmp/postgrades.mail.$USER.$$

set PRIVATE = "NUMBER COR CO1 CO2 CO3"
set msgnum = ""
if ($1 == "-initial") then
  set msgnum = 1
  set PRIVATE = "COR CO1 CO2 CO3"
  shift
endif

set filebase = $1:r

if (-e $filebase.private) then
  set PRIVATE = "$PRIVATE `cat $filebase.private`"
endif

# Following two lines obsolete from when did paper posting
# stripgradestats $filebase.txt | egrep -v 'EMAIL|FAX' | excol -v NAME EADDR CLS $PRIVATE | grep -v NOBODY > $filebase-post.txt
# stripgradestats $filebase.txt | excol NAME NUMBER COR CO1 CO2 CO3 > $filebase-core.txt

set dir = "`pwd`"
set semester = $dir:t
set headofdir = $dir:h
set course = $headofdir:t

echo "Content-Transfer-Encoding: 7bit" > pgmsg.txt
echo 'Content-Type: multipart/mixed; boundary="MIMEBDRY"' >> pgmsg.txt
echo "MIME-Version: 1.0" >> pgmsg.txt
echo "From: $REALNAME <$EADDR>" | sed 's+@math\.luc\.edu+@cs.luc.edu+' >> pgmsg.txt
echo "Subject: $course $semester $filebase record" >> pgmsg.txt
echo '' >> pgmsg.txt
echo "This is a multi-part message in MIME format" >> pgmsg.txt
echo '' >> pgmsg.txt
echo "--MIMEBDRY" >> pgmsg.txt
echo "Content-Transfer-Encoding: 7bit" >> pgmsg.txt
echo "Content-Type: text/html" >> pgmsg.txt
echo '' >> pgmsg.txt
echo "<PRE>" >> pgmsg.txt
cat ${filebase}msg${msgnum}.txt >> pgmsg.txt

cat $filebase.txt | egrep 'NAME|EMAIL' | excol -v POST CLS $PRIVATE | grep -v NOBODY > $tmpmail
set addrs = (`cat $tmpmail | excol EADDR`)
head -n 1 $tmpmail >> pgmsg.txt
if ($msgnum != 1) then
  grep POSSIBLE $tmpmail >> pgmsg.txt
endif
cat $tmpmail | tail -n +2 | pginternal egr $addrs[2-]

cat $filebase.txt | egrep 'NAME|FAX' | excol -v POST CLS $PRIVATE | grep -v NOBODY > $tmpmail
set addrs = (`cat $tmpmail | excol NAME EADDR | tr -s '' ' ' | tr ' ' '_'`)
# Can replace above line with following line if mailaddrs command has been run.
# set addrs = (`cat faxdests | tr ' ' '_'`)
cat $tmpmail | tail -n +2 | pginternal fgr $addrs[2-]

rm -f $tmpmail pgmsg.txt
