#! /bin/bash

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

# Compares all files under the current directory "./" that have a similarly named
# version in "${HOME}/". Writes the concatenated "prdiff" output to stdout.

# Ignores files whose names end in "~".

dirs=( "$@" )
if [[ ${#dirs[@]} -eq 0 ]]; then dirs=( ./ ); fi

# 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 ${dirs[@]} -type f -print \
    | sed \
        -e '/[~]$/d' \
        -e 's:^[.][/]::' \
    | sort 
  ` )
echo "!! ${#files[@]} files found." 1>&2

dfile="${tmp}_deleted.txt" # Concatenated diffs.
touch ${dfile}

for f in "${files[@]}" ; do 
  echo "=== ${f} ===" >> ${dfile}
  hfile="${HOME}/$f"  # File in ${HOME}.
  afile="./$f"        # File in this mirror directory.
  if [[ ! ( -r "${hfile}" ) ]]; then
    echo "!! no ${f} in HOME" >> ${dfile}
  else
    if [[ ! ( -r "${afile}" ) ]]; then
      echo "** bug ${afile}" 1>&2; exit 1
    fi
    echo " < = ${hfile} " >> ${dfile}
    echo " > = ${afile} " >> ${dfile}
    echo " " >> ${dfile}
    prdiff -Bb "${hfile}" "${afile}" >> ${dfile}
  fi
done

cat ${dfile}
rm ${dfile}
