#!/usr/bin/env bash

# Import grades into grades.sc from $1-grade.txt files on .graded subdirectories
# of subdirectories of hwsubmit/core.
# Looks for line with "Total" (case insensitive) and then two numbers separated by "/" and possibly spaces.
# With no submission on same line, will lead to special "NS" entry in spreadsheet instead of just 0.
# Makes a backup of grades.sc on .del
# Does not matter if there are more $1-grade.txt files than students in spreadsheet (i.e., for students who have dropped)

# $var:t    ${var##*/}
# $var:h    ${var%/*}
# $var:e    ${var##*.}
# $var:r    ${var%.*}
 
debug=1

tempfile=/tmp/gradesinsc.$USER.$$.awk

if [[ $# -lt 1 ]]; then
  echo "Usage: gradesinsc hwnum [flag]"
  exit 1
fi

collet=`sed -n 's+.* \([A-Z][A-Z]*\)[0-9][0-9]* = "'HW$1'"+\1+p' grades.sc` # Like sakai2grades but w HW specified

echo 'BEGIN {' > $tempfile # Generating awk program to associate grades with email addresses
\grep -wi 'total' hwsubmit/core/*/.graded/$1-grade.txt | downcase \
  | \grep -v 'no submission' \
  | sed -n 's+.*/\([^/]*\)/.graded/.*total[: 	]*\([0-9][0-9]*\) */ *[0-9][0-9]*.*+score["\1"]=\2;+p'\
  | sed 's+score\["\([^@]*\)"\]=+score["\1@luc.edu"]=+' \
  >> $tempfile
echo '}\
{ if (score[$2]!="") print "let '$collet'"$1" = "score[$2]; else print "rightstring '$collet'"$1" = \"NS\""; }' >> $tempfile

if (( $debug )) ; then cat $tempfile; fi

del . grades.sc
cp .del/grades.sc . # Backed up grades.sc

# Following sends linenum/email pairs to awk program
make grades.txt
stripgradestats grades.txt | excol EADDR | tail +2 | numlines | tr -d : | awk -f $tempfile >> grades.sc

rm $tempfile
