#!/bin/csh

# Files required to run:
# assignments:	List of students and their assignments, one per line
#	sample: "meepcat 21M602  1  "
# classes:	List of classes from which students have made their choices
#	sample: "21L009  1  21L009   Sec 1 Shakespeare MW 11 - 12:30"
# goodmessage:	Vanilla message sent out to assigned students
# badmessage:	Limbo message to those not assigned


# Necessary input files.
set assignments = /var/pelott-dev/data/assign.txt
set classes = /var/pelott-dev/data/lotclass.txt
set goodmessage = /var/pelott-dev/data/email1.txt
set badmessage = /var/pelott-dev/data/limbo1.txt

# Root of the assignment directory tree.
set assignmentroot = /afs/athena.mit.edu/astaff/project/pelott/assignments

#Temporary working files:
set sorted = /var/pelott/assign.sort
set loginlist = /var/pelott/logins.sort
set logfile = /var/pelott/builddir.log

rm $logfile
echo "Building directories, started at "`date` > $logfile

rm $sorted
sort $assignments > $sorted
cat $sorted | cut -c1-8 >! $loginlist

foreach user (`cat $loginlist`)
	set assignmentdir = $assignmentroot/$user
	mkdir $assignmentdir
	fs sa $assignmentdir $user read

	set awkfile = tempawk.awk.$$
	set assignmentfile = $assignmentdir/assign
	set okflag = 1
	echo "Finding assignment for" $user

	set short = `awk '{print}' $sorted | grep -w $user`

	if ( $status ) then
		set num = `echo $user | wc -c`
		if ( $num == 9 ) then
			set short = `grep $user $sorted`
			if ( $status ) then
				echo "$user not found in assignment file"
				set okflag = 0
			else
				set assignment = `echo "$short" | cut -c9-18`
			endif
		else
			echo "$user not found in assignment file"
			set okflag = 0
		endif
	else
		set assignment = `echo "$short"` 
		shift assignment
	endif
	if ( $okflag == 1) then
		echo $user is assigned to class $assignment[1] section $assignment[2]
# Did he wind up in limbo?

	if ( $assignment[1] == "NONE" ) then
		set okflag = 0
	else
		echo '$1 ==' \"$assignment[1]\" '&& $2 ==' $assignment[2] '{ print }' >! $awkfile
		set classname = "`awk -f $awkfile $classes | cut -c12-`"
		set okflag = 1
	endif
endif


	if ( $okflag ) then
		echo "You have been assigned the following class by the PE lottery program:" > $assignmentfile
		echo "" >> $assignmentfile
		echo $classname >> $assignmentfile
		echo "" >> $assignmentfile
		cat $goodmessage >> $assignmentfile
	else
		cat $badmessage > $assignmentfile
	endif
	echo `date` $user >> $logfile
end
rm $sorted
rm $loginlist
