#!/bin/sh

# diff_local_remote_dirtree.sh
# 2011-07-17
# by Gernot WALZL

# Checks if the directory tree and its contents of a given directory
# on the local system are equal on a remote system.

DIR_LOCAL=${DIR_LOCAL:-"/home/gernot"}
DIR_REMOTE=${DIR_REMOTE:-"/home/gernot"}
HOST=${HOST:-"E6850"}

TMP=$(mktemp -d)

diff_dirtree () {
  cd "$DIR_LOCAL" && find . -type d | sort > "$TMP/local"
  ssh "$HOST" "cd \"$DIR_REMOTE\" && find . -type d | sort" > "$TMP/remote"
  cd $TMP
  diff -u local remote > dirtree.diff
  rm local remote
}

diff_dirtree_contents () {
  cd "$DIR_LOCAL" && find . -type f -print0 | sort -z | xargs -0 md5sum > "$TMP/local"
  ssh "$HOST" "cd \"$DIR_REMOTE\" && find . -type f -print0 | sort -z | xargs -0 md5sum" > "$TMP/remote"
  cd $TMP
  diff -u local remote > dirtree_contents.diff
  rm local remote
}

diff_dirtree
if [ $(cat "$TMP/dirtree.diff" | wc -l) -eq 0 ]; then
  diff_dirtree_contents
  cat "$TMP/dirtree_contents.diff"
else
  cat "$TMP/dirtree.diff"
fi
rm -rf "$TMP"