#!/bin/csh -f

# For each argument, as created with sc2txt from my standard type of
# grade spreadsheet (e.g., foo.txt), create foo.mailrc containing an
# alias for the students in the class who have an email address in
# foo.txt plus graders.  The alias is $course$semester, where $course
# and $semester are inferred from the directory path name.  Grader
# information is obtained from foo.access, each line of which gives a
# person type (grader, colleague, etc.), an email address, and a PIN.
# Any person type containg "grader" is used to create an alias <person
# type>$course$semester.  If anybody has person type exactly equal to
# "grader", the entry grader$course$semester is added to the
# $course$semester alias.  (The same person can appear with more than
# one person type.)  Any extension given in the file name arguments
# are ignored.

# Also creates a list of fax destinations on foo.faxdests suitable for
# the faxlist command for those people who have a fax number in foo.txt.

# With no arguments, assume grades.txt

set files = ($*)
if ($#argv == 0) then
  set files = grades.txt
  make grades.txt
endif

foreach file ($files)
  if (! -e $file) break
  set gradesfile = `echo $file | sed 's+^\([^/]\)+./\1+'`

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

  echo '' > $gradesfile:r.mailrc # Make initial blank line to keep ~/.mailrc pretty

  if (! -e $gradesfile:r.access) touch $gradesfile:r.access
  awk '$1 ~ /grader/ {print "alias", $1 "'$course$semester'", $2}' \
      $gradesfile:r.access >> $gradesfile:r.mailrc

  echo -n "alias $course$semester " >> $gradesfile:r.mailrc
  egrep 'EMAIL|NAME' $gradesfile:r.txt | excol EADDR | tail -n +2 \
    | tr -d ' ' | tr '\012' ' ' >> $gradesfile:r.mailrc
  if (`grep -c "^alias grader$course$semester" $gradesfile:r.mailrc` != 0) echo -n "grader$course$semester" >> $gradesfile:r.mailrc

  echo '' >> $gradesfile:r.mailrc # Just to put linebreak at end of last line

  egrep 'FAX|NAME' $gradesfile:r.txt | excol NAME EADDR | tail -n +2 \
  | tr -s '' ' ' >> $gradesfile:r.faxdests

end
