#! /bin/bash

# To be executed in a "${aula}/pun" directory (checkout of project just
# after class, with trunk (master branch) as handed out and all student
# branches still un-merged.

# Deletes all files in "branches/${ra}/" that are identical to their
# versions in "trunk/". Writes the list of deleted important files
# (excluding "README.md", "LICENSE", etc.) to "${repdir}/${ra}.dels"

aula="$1"; shift # Date of class, "{YYYY}-{MM}-{DD}"
if [[ "/${aula}" == "/" ]]; then echo "{aula} not specified" 1>&2 ; exit 1; fi

# Get student IDs:
ras=( "$@" )
 
repdir=${HOME}/cursos/mc857/2020-1/notas/ra
if [[ ! ( -d ${repdir} ) ]]; then
  echo "** directory ${repdir} does not exist or is not a directory" 1>&2
  exit 1
fi

mc857_check_current_dir_2.sh "${aula}/pun" || exit 1

# Get the names of files in "trunk", to compare against:
files=( `cd trunk && find ./ -type f -print | sed -e 's:^[.][/]::'` )
echo "!! files found:" 1>&2
for f in "${files[@]}" ; do 
  tfile="trunk/$f"
  echo "${tfile}" 1>&2
done

for ra in ${ras[@]}; do 
  bra="branches/${ra}"
  
  mkdir -p "${repdir}/${ra}/${aula}"
  dlist="${repdir}/${ra}/${aula}/deleted-files.txt" # Log of files deleted.
  if [[ -e ${dlist} ]]; then
    echo "** file ${dlist} already exists; appending" 1>&2
  else
     touch ${dlist}
  fi
  
  if [[ ! ( -d ${bra} ) ]]; then
    echo "** ${bra} missing or not a directory" 1>&2
    echo "** BRANCH MISSING **" >  ${dlist}
  else
  
    echo "!! deleting unimportant files of ${bra}"  1>&2
    rm -rfv __pycache__ DB testes/saida
    rm -fv .gitignore LICENSE README.md testa.sh Makefile 
    rm -fv modulos*.txt 00-MODULOS*.txt tarefas*.txt
    rm -fv testes/{README.md,imagens,Makefile,testa.sh}
    rm -fv relatorios/README.md relatorios/*/README.md
    
    echo "!! deleting unchanged files of ${bra}"  1>&2
    for f in "${files[@]}" ; do 
      tfile="trunk/$f"
      bfile="${bra}/$f"
      if [[ -r "${bfile}" ]]; then
        if cmp -s "${tfile}" "${bfile}" ; then
          # Files are equal, delete the branch copy:
          rm ${bfile}
          echo "deleting ${bfile}" 1>&2
          echo "removed ${bfile}" >> ${dlist}
        fi
      fi
    done
    ls -l ${bra} ${bra}/testes
  fi
done


