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

PROG_NAME=${0##*/}
PROG_DESC="creates all necessary links (Makefiles, absent images etc) to run student homeworks."
PROG_HELP=(
  "${PROG_NAME} {LABDIR}"
)
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 RA\n"
  "numbers and usernames of all students.\n\n"
  "\n"
  "This script is mostly obsolete since the scripts {fetch-labday-files}\n"
  "and {fetch-student-files} already create the necessary links.\n"
)

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

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

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

labdir="$1"; shift

if [[ ! ( -d ${labdir} ) ]]; then
  echo "directory ${labdir} not found" 1>&2; exit 1
fi

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

tpdir="${labdir%%/*}"

# Make sure that main files exist in the all-hand-ins directory:
for f in \
  rausrs.txt ras.txt eixos.inc nuvens.inc
do
  if [[ ! -e ${tpdir}/../${f} ]]; then
    echo "warning: missing ${tpdir}/../${f}"; bug=1
  fi
done

# Make sure that main files specific for this lab project:
for f in \
  rausrs.txt ras.txt \
  eixos.inc
do
  if [[ ! -e ${tpdir}/${f} ]]; then
    ( cd ${tpdir} && ln -s ../${f} )
  fi
done

bug=0
for f in \
  Makefile aus.txt title.txt \
  camlight.inc
do
  if [[ ! -e ${tpdir}/${f} ]]; then
    echo "warning: missing ${tpdir}/${f}"; bug=1
  fi
done

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

# Make sure that there are links/files peculiar to each student's directory:
rausrs=( `cat ${labdir}/rausrs.txt | egrep -v '^ *([#]|$)' | gawk '//{print $1 "." $2;}' ` )
for rausr in ${rausrs[@]} ; do 
  ra="${rausr##*.}"
  usr="${rausr%.*}"
  echo "Creating links for ra=${ra} usr=${usr}"
  
  # Create hand-in subdirectory for student
  todir="${labdir}/${ra}"
  if [[ ! ( -d ${todir} ) ]]; then mkdir ${todir}; fi
  # Create necessary links:
  for f in \
    Makefile \
    camlight.inc eixos.inc
  do
    if [[ ! ( -e ${todir}/${f} ) ]]; then
      ( cd ${todir} && ln -s ../${f} )
    fi
  done
done