#! /bin/bash 
# Last edited on 2010-12-14 20:45:30 by stolfilocal

USAGE="${cmd} aula|casa {SITE} "

# Finds all "main-orig.pov" files under current directory.
# Scans them for ".inc" or image files.
# Writes the fetch commands to fetch those files from {SITE} to ".fetch-{which}-aux-files".
# Requires the files "rausrs.txt" and "labs-info.txt" in the current directory.

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

which="$1"; shift;
site="$1"; shift;

tmp="/tmp/$$"

# Grab the names and dates of the labs:
tpnames=( )
tpdates=( )
for name in `cat labs-info.txt | gawk '/^[ ]*([\#]|$)/{ next; } (NF>=2){ print $1; }'` ; do
  tpnames=( "${tpnames[@]}" "${name}" );
done
i=0
for date in `cat labs-info.txt | gawk '/^[ ]*([\#]|$)/{ next; } (NF>=2){ print $2; }'` ; do
  tpdates=( "${tpdates[@]}" "${date}" );
done

ras=(  `cat rausrs.txt | gawk '/^[ ]*([\#]|$)/{ next; } //{ print $2; }'` );
usrs=( `cat rausrs.txt | gawk '/^[ ]*([\#]|$)/{ next; } //{ print $1; }'` );

# Enumerate all students and "main.pov" files:
cmdfile=".fetch-${which}-aux-files"
/bin/rm -f ${cmdfile}

for i in `count 0 $(( ${#tpdates[@]} - 1 ))` ; do
  echo ${tpnames[$i]} ${tpdates[i]} 1>&2
  tp="${tpnames[$i]}"
  td="${tpdates[$i]}"

  for j in `count 0 $(( ${#ras[@]} - 1 ))` ; do
    ra="${ras[${j}]}"
    usr="${usrs[${j}]}"
    echo "  ${ra} ${usr}" 1>&2
    povfile="${tp}/${which}/${ra}/main.pov"
    if [[ -s ${povfile} ]]; then
      cat ${povfile} \
        | sed -e 's:["]\(.*\)[.]\(.*\)["]:%@@@\1.\2%:g' \
        | tr '%' '\012' \
        | grep -e '@@@' \
        | sed -e 's:@@@::g' \
        > ${tmp}.aux

      for f in `cat ${tmp}.aux` ; do 
        if [[ ( "/${f}" != "/camlight.inc" ) ]]; then 
          printf "fetch-student-files ${tp}/${which} ${ra} ${site} ${usr} mc930/${td} ${f}\n" >> ${cmdfile}
        fi
      done
    fi
  done
done

rm -f ${tmp}.aux

echo "=== done ==="