#! /usr/bin/env bash

# Import grades into grades.sc from Sakai gradebok export to be named as fromsakai.csv
# $1 specifies destination column name, and $2 specifies source column name (with spaces and bracketed content removed).
# Assumes 0 in Sakai is NS for my spreadsheet; same should happen with grades absent in Sakai.
# If $3 is set, use data from source to update width of destination column.
# Makes a backup of grades.sc on .del

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

debug=0

tmpfile1=/tmp/sakai2grades1.$USER.$$
tmpfile2=/tmp/sakai2grades2.$USER.$$
tmpfile3=/tmp/sakai2grades3.$USER.$$

if [[ $# -lt 2 ]]; then
  echo "Usage: sakai2grades DESTCOL SRCCOL [flag]"
  exit 1
fi

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

if (( $debug )); then echo collet: $collet; fi

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

# dos2unix -F fromsakai.csv
sed 's+\[[^[]*\]++g' fromsakai.csv | csv2txt | tee $tmpfile1 | excol "Student-Name" | sed 's+^ *++' | sed 's+,-+,+' | sed 's+-.*++' | tail +2 > $tmpfile2
if (( $debug )); then echo "head of fromsakai csv2txt"; head -5 $tmpfile1; fi
if (( $debug )); then echo "head of fromsakai Student Names"; head -5 $tmpfile2; fi
make grades.txt; echo
stripgradestats grades.txt | excol NAME | sed 's+^ *++' | sed 's+, +,+' | sed 's+ .*++' | tail +2 > $tmpfile3
if (( $debug )); then echo "head of shortened grades.txt names"; head -5 $tmpfile3; fi
if ( diff -b $tmpfile2 $tmpfile3 ); then # want same IDs in grades.txt & fromsakai.csv
  cat $tmpfile1 | excol "$2" | tail +2 | tr -d ' ' | tee $tmpfile2 | awk '{print "rightstring '$collet'"NR" = \""$1"\"";}' | sed 's+rightstring \(.*\) = "\([0-9]*\)"$+let \1 = \2+' | sed 's+^let \(.* = \)0\?$+rightstring \1"NS"+' >> grades.sc
  if (( $debug )); then echo "head of column extracted from fromsakai"; head -5 $tmpfile2; fi
  if [[ $# -ge 3 ]]; then
    colwidth=`cat $tmpfile2 | wc -L`
    colwidth=`expr $colwidth + 1`
    echo format $collet $colwidth 0 0 >> grades.sc
  fi
  echo "Modified grades.sc."
else
  echo "Mismatch of IDs in files; grades.sc not changed."
fi

if (( ! $debug )); then rm -f /tmp/sakai2grades*.$USER.$$; fi
