#!/bin/sh -
#
# submit Cadence hardware lab work
#
umask 077
progname=`basename $0`
cwd=`pwd`
CF=/vol/vlsi/local/lib/$GROUP/handin.cf
tmp=/tmp/$progname.hn.$$
tmpdir=/tmp/$progname.orig.$$
trap 'rm -rf $tmp $tmpdir' 0 1 2 3 15

# check it's not the home directory (embarrassing to receive private things
#  like .mail, .Xauthority, even by mistake!)
if [ `basename $cwd` = `whoami` ]; then
	echo You are not in a Cadence exercise directory. >&2
	exit 1
fi

# further check on sensible location
if [ `echo $cwd | grep -c $USER` -lt 1 ]; then
	echo Permission Denied. >&2
	exit 1
fi
if [ $# -ne 1 ]; then
	echo "Usage: $progname exercise_no" >&2
	exit 1
fi
if [ ! -f $CF -o ! -r $CF ]; then
	echo "$progname: No configuration file - contact your lab organiser." >&2
	exit 1
fi
exno=$1
line=`sed '/^[ 	]*#/d' $CF | grep "^$exno[ 	]"`
 #note: SPACE TAB inside the square brackets
dest=`echo $line | (read w x y; echo $x)`
files=`echo $line | (read w x y; echo $y)`
# echo files are: $files
if [ -z "$files" ]; then
	echo "$progname: No entry in configuration file for exercise $exno" >&2
	exit 1
fi
echo "Exercise $exno:"
mustexist=""
for f in $files; do
	# echo -n "  $f: "
	if [ -f $f -a -r $f ]; then
		mustexist="$mustexist $f"
		# echo "ok."
	#else #empty else apparently illegal in sh!
		# echo "missing or not readable."
	fi
done
# the following echo arrangement standardizes the tedious whitespace
# differences in $mustexist vs. $files
if [ "`echo $mustexist`" != "`echo $files`" ]; then
	echo "$progname: you are not in a finished Cadence directory!!" >&2
	exit 1
fi
rm -rf $tmp $tmpdir
mkdir $tmpdir
cp -pr . $tmpdir/submission
if [ $? -ne 0 ]; then
	echo "$progname: Could not create archive of submitted work - seek help" >&2
	exit 1
fi
cd $tmpdir
tar cf $tmp submission 2>/dev/null
if [ $? -ne 0 -o ! -f $tmp -o ! -s $tmp ]; then
	echo "$progname: Could not create archive of submitted work - seek help" >&2
	exit 1
fi
btoa < $tmp | mail -s "Jabberwocky says: submitcad $exno" $dest
# Jabberwocky standard used by receiving mailfilter: do not change!
echo "Cadence Exercise $exno submitted by $USER on `date`"
echo "Confirmation will be returned by e-mail."
exit 0
