#! /bin/bash

# To be executed in a sub-directory of "00-MIRROR" directory.

# Deletes all files under the current directory "./" that are identical to their
# versions in "${HOME}/". Writes the list of deleted files
# to standard out.

# The files are not actually deleted, but are renamed with a "~@~" extension.
# Ignores files whose names end in "~".

# Check that it is being executed in the right directory:
parentdir="`cd .. && pwd`"
parentdir="${parentdir##*/}"
if [[ "${parentdir}" != "00-MIRROR" ]]; then
  echo "** wrong directory, should be 00-MIRROR/{XXX}" 1>&2
  exit 1
fi

tmp="/tmp/$$" # Temp file prefix

# Get the names of files to compare:
files=( `find ./ -type f -print | sed -e '/[~]$/d' -e 's:^[.][/]::'` )
echo "!! ${#files[@]} files found:" 1>&2

dlist="${tmp}_deleted.txt" # Log of files deleted.
touch ${dlist}

for f in "${files[@]}" ; do 
  hfile="${HOME}/$f"  # File in ${HOME}.
  afile="./$f"        # File in this mirror directory.
  if [[ ! ( -r "${hfile}" ) ]]; then
    echo "!! no ${f} in HOME" 1>&2
  else
    if [[ ! ( -r "${afile}" ) ]]; then
      echo "** bug ${afile}" 1>&2; exit 1
    fi
    if cmp -s "${hfile}" "${afile}" ; then
      # Files are equal, delete ${afile}
      mv "${afile}" "${afile}~@~"
      echo "deleting ${afile}" 1>&2
      echo "${afile}" >> ${dlist}
    fi
  fi
done

cat ${dlist}
rm ${dlist}
