#!/bin/sh -
#
# Receive Cadence hardware lab course work.
#
# Run from a .mailfilter which checks subject line is
#	"Jabberwocky says: submitcad <raw_exno>"
# and runs this script with arguments '$(return_path)' ---the bona fide sender
#				  and '$(subject)'     ---the subject line.
#
# WARNING: always exit 0 even in the case of errors. Otherwise the mail system
#  keeps trying, and trying, and trying..... (see man mailfilter).
#

# sh doesn't pick up $LOCALLAB, so.....
LOCALLAB=/vol/lab export LOCALLAB

ADMIN=/vol/vlsi/local/admin #or wherever this file (and rc_add_to_log)
			    #will be put
PATH=/bin:/usr/bin:/usr/ucb:/usr/local/bin:/usr/public/bin:$LOCALLAB/firstyear/bin:$LOCALLAB/firstyear/bin/`/bin/arch`:$LOCALLAB/bin:$LOCALLAB/bin/`/bin/arch`:$ADMIN/bin:$ADMIN/bin/`/bin/arch` export PATH
progname=`basename $0`
umask 027

#
# HANDIN is the directory in which the course work submissions are to
#  be stored
#
HANDIN=/vol/vlsi/local/handin export HANDIN
mkdir -p $HANDIN
chmod 750 $HANDIN #paranoid security check

temp=$HANDIN/.rc_temp_directory
mkdir -p $temp

binary_archive=$temp/rc_binary_archive.$$
errors=$temp/rc_errors.$$
temp_receipt_log=$temp/rc_temp_receipt_log.$$
 rm -f $temp_receipt_log
 touch $temp_receipt_log
warnings=$temp/rc_warnings.$$

#
# send problem reports to POORSOD
#
POORSOD=$USER

trap 'trap "" 0 1 2 3 15; rm -f $errors $binary_archive $temp_receipt_log $warnings; exit 0' 0 1 2 3 15

if [ $# -ne 2 ]; then
	echo "	Internal error of $progname at `/bin/date` - \$\# = $#" >>$temp_receipt_log
	(
		echo "The mailfilter must be broken, at `/bin/date`"
		echo "a submission (args = $*) was therefore lost!!!"
	) | mail -s "$progname: mailfilter error" $POORSOD
	mkdir -p $HANDIN/.handin_from_persons_unknown
        rc_add_to_log $temp $HANDIN/.handin_from_persons_unknown $$
	exit 0
fi

from="$1"
subject="$2"

#
# first say we received message.....
#
echo "$progname: submission from $from at `date`" >> $temp_receipt_log

#
# Save errors to $errors and warnings to $warnings
#
rm -f $warnings $errors
touch $warnings
exec 2> $errors
#
#
#
# Figure out student name from source address, which should be student@domain.
#
student="`expr $from : '\([^@]*\)'`"
cadgroup=`show_cadgroup_of $student`
if [ $? -ne 0 ]; then
  echo "	Submission from unidentified student $student [full mail address is $from] at `/bin/date`" >>$temp_receipt_log
  (
    echo "Submission from unidentified student $student [full mail address is $from] at `/bin/date`"
    echo "submission was therefore lost."
  ) | mail -s "$progname: source address error" $POORSOD
  mkdir -p $HANDIN/.handin_from_persons_unknown
  rc_add_to_log $temp $HANDIN/.handin_from_persons_unknown $$
  exit 0
fi

#
# SUBDIR is the directory for the cadgroup in question's submissions to
#  be stored
#
SUBDIR=$HANDIN/$cadgroup export SUBDIR
mkdir -p $SUBDIR
#
# log file to log _all_ received submissions (even unsuccessful attempts)
#  will be $SUBDIR/.receipt_log
#

#
# CF - the name of the (cadgroup-oriented) handin configuration file
# This will normally be a slave copy of, or symlink to, the (Unix)-group-
# -oriented handin configuration file used by submitcad.
#
CF=/vol/vlsi/local/lib/$cadgroup/handin.cf
if [ ! -f $CF ]; then
  echo "	Configuration file $CF not found at `/bin/date`" >>$temp_receipt_log
  (
    echo "Configuration file $CF not found at `/bin/date`"
    echo "a submission (from $from) was therefore lost."
  ) | mail -s "$progname: configuration file error" $POORSOD
  rc_add_to_log $temp $SUBDIR $$
  exit 0
fi

#
# get raw exercise no. from subject line
#
raw_exno=`echo $subject | grep '^Jabberwocky says: submitcad [0-9][0-9]*$' | sed 's/^Jabberwocky says: submitcad //'`
if [ "$raw_exno" = "" ]; then
  echo "	Suspect subject line $subject found at `date`" >>$temp_receipt_log
  (
    echo "Suspect subject line $subject found at `date`"
    echo "a submission (from $from) was therefore lost."
  ) | mail -s "$progname: subject line error" $POORSOD
  rc_add_to_log $temp $SUBDIR $$
  exit 0
fi
echo "	Submission is for raw exercise no. $raw_exno" >>$temp_receipt_log

#
# get expected filenames from configuration file (though just to see if it's
# a valid listed exercise---we don't currently *use* these filenames at the
# receiving end, as the whole directory was tarred at the sending end!)
#
line=`sed '/^[ 	]*#/d' $CF | grep "^$raw_exno[ 	]"`
 #note: SPACE TAB inside the square brackets
files=`echo $line | (read w x y ; echo $y)`
if [ "$files" = "" ]; then
  echo "	No files in $CF for raw exercise no. $raw_exno at `date`" >>$temp_receipt_log
  (
    echo "No files in $CF for raw exercise no. $raw_exno at `date`"
    echo "a submission (from $from) was therefore lost."
  ) | mail -s "$progname: no-files-listed error" $POORSOD
  rc_add_to_log $temp $SUBDIR $$
  exit 0
fi

exercise=$raw_exno #they could be different in a system with names, say
nontrivsub=FALSE #provisional. ...non-trivial submission (at least one file)

if [ -f $SUBDIR/.lock.$exercise ]; then
	echo "The hand in date for Cadence Exercise $raw_exno has passed." >&2
	echo "Please see your Cadence lab organiser." >&2
	echo "	Submission rejected because handin date is passed" >>$temp_receipt_log
else
	case $student in
	""|*/*|*.*)
		echo "You don't seem to have submitted the work using the \"submitcad\" program." >&2
		echo "	Submission rejected - bad student login name??" >>$temp_receipt_log
		;;
	*)
		student_loc=$SUBDIR/$exercise/$student
		mkdir -p $student_loc
		cd $student_loc

                # START CRITICAL REGION
                until tas .busy; do
                  sleep 2
                done

                # we've bagged it!

                # START NAKED TASK
		echo "	Placing files in $student_loc at `/bin/date`" >>$temp_receipt_log
		rm -rf .scratchpad
		mkdir .scratchpad
		cd .scratchpad
		#
		# Strip off the mail header. (standard input consumed here)
		#
		sed '1,/^$/d' | atob > $binary_archive
		#
		# Extract all the files from
		# the archive.
		#
		files=submission.tar #let's just use this name for now
		for f in $files; do
			#ar x $binary_archive $f
			cat $binary_archive > $f ###i.e., no automated
						 ###"untarring" (security!)
			if [ -f $f ]; then
				# accept this file, by putting it into the
				# proper position.
				rm -f ../$f
				cp $f ../$f
				chmod 440 ../$f
			fi
		done
                echo "	Files received: `ls | tr -s '\012' ' '`" >> $temp_receipt_log
		if [ "`ls`" != "" ]; then
			nontrivsub=TRUE
		fi
		#
		# Now generate errors for any files that didn't arrive
		#
		for f in $files; do
			if [ ! -f $f ]; then
                          echo "File $f not received in this submission" >&2
          		fi
		done
		cd ..
		rm -rf .scratchpad
                # END NAKED TASK

                # we've finished!
                rm -f .busy

                # END CRITICAL REGION
		;;

	esac
fi

exec 2>&1
if [ ! -s $errors -o $nontrivsub = TRUE ]; then #we count errors as warnings...
	cat $warnings >> $errors ; mv $errors $warnings ; touch $errors
	echo "	Submission accepted." >> $temp_receipt_log
	echo "Message from auto-submit system (ie, automatically generated)....."
	echo "Your submission for Cadence Exercise $raw_exno was accepted."
	echo ''
	if [ -s $warnings ]; then
		echo "Warning:"
		cat < $warnings
		echo ''
		(
		echo "	Warnings:"
		sed 's/^/	/' < $warnings
		) >>$temp_receipt_log
	fi
        echo "Files received from you so far for this exercise:"
	ls -l
else
	(
	echo "	Submission rejected---reason:"
	sed 's/^/	/' < $errors
	) >>$temp_receipt_log
	echo "Message from auto-submit system (ie, automatically generated)....."
	echo "Your submission for Cadence Exercise $raw_exno was rejected for the following reason:"
	echo ''
	cat $errors
fi |
mail -s "Your submission for Cadence Exercise $raw_exno" $from
rc_add_to_log $temp $SUBDIR $$
rm -f $errors $binary_archive $temp_receipt_log $warnings

exit 0
