#! /bin/bash
# Last edited on 2010-07-08 18:37:31 by stolfilocal

export PATH="tools:../tools:../../tools:../../../tools:../../../../tools:${PATH}"

PROG_NAME=${0##*/}
PROG_DESC="fetch all MC930 homework files for a single day and all students"
PROG_HELP=(
  "${PROG_NAME} [-check] {LABDIR} {EXDIR} [{FILE}...]"
)
PROG_INFO=(
  "\nNAME"
  "\n  ${PROG_NAME} - ${PROG_DESC}."
  "\n"
  "\nSYNOPSIS"
  "\n  ${PROG_HELP[@]}"
  "\n"
  "\nDESCRIPTION"
  "\n"
  "The {LABDIR} must be \"tpXX/casa\" or \"tpXX/aula\"\n"
  "\n"
  "Requires a file \"{LABDIR}/rausrs.txt\" with the usernames\n"
  "and RA numbers of all students.\n"
  "\n"
  "Fetches the named {FILE}s of all students, from the HTTP directory\n"
  "\"http://www.students.ic.unicamp.br/~{USR}/${EXDIR}/\"\n"
  "to the local directory \"{LABDIR}/{RA}/\"\n"
  "where {RA} is the student's RA number.\n"
  "Also creates copy of every file, with the suffix \"-orig\" appended,\n"
  "in preparation of editing and re-rendering by the instructor.\n"
  "\n"
  "If \"-check\" is given, only checks which files exist, does not fetch \n"
  "anything.\n"
)

checkopt=( );
while [[ ( $# -ge 1 ) && ( "/$1" =~ "/-.*" ) ]]; do
  if [[ ( $# -ge 1 ) && ( "/$1" == "/-check" ) ]]; then
    checkopt=( "-check" ); shift; 
  else
    echo "usage ${PROG_HELP}" 1>&2; exit 1
  fi
done

if [[ $# -lt 2 ]]; then
  echo "usage ${PROG_HELP}" 1>&2; exit 1
fi

labdir="$1"; shift
exdir="$1"; shift

if [[ $# -lt 1 ]]; then
  echo "no files to fetch?" 1>&2;
  echo "usage ${PROG_HELP}" 1>&2; exit 1
fi

files=( "$@" )
echo "fetching files ${files[@]}" 1>&2;

if [[ ( "/${labdir##*/}" != "/aula" ) && ( "/${labdir##*/}" != "/casa" ) ]]; then
  echo "directory ${labdir} should be */aula or */casa" 1>&2; exit 1
fi

# Reset the wget log file:
wlog="${labdir}/wget-log.txt"
if [[ -r ${wlog} ]]; then
  mv -v ${wlog} ${wlog}.`date -r ${wlog} +%Y-%m-%d-%H%M%S`
fi
touch ${wlog}

# Make sure that there are links to files peculiar to this homework:
for f in \
  Makefile \
  missing.png missing-i.png \
  absent.png absent-i.png \
  rausrs.txt aus.txt title.txt \
  camlight.inc
do
  if [[ ! -e ${labdir}/${f} ]]; then
    ( cd ${labdir} && ln -s ../${f} )
  fi
done

# Fetch files of all students
rausrs=( `cat ${labdir}/rausrs.txt | egrep -v '^ *([#]|$)' | gawk '//{print $1 "." $2;}' ` )
site="www.students.ic.unicamp.br"
for rausr in ${rausrs[@]} ; do 
  ra="${rausr##*.}"
  usr="${rausr%.*}"
  echo "Fetching ra=${ra} usr=${usr}"
  fetch-student-files ${checkopt[@]} ${labdir} ${ra} ${site} ${usr} ${exdir} "${files[@]}"
done