#!/bin/sh -e
#
# dirsum PATHS... - compute order-invariant hash for given files/directory
# only takes file names and contents into account
#
# ---
# source: https://leahneukirchen.org/dotfiles/bin/dirsum

export LC_ALL=C

if command -v sha256sum >/dev/null; then
  SUM="sha256sum --tag"
elif command -v sha256 >/dev/null; then
  SUM="sha256"
else
  echo "no hash tool found" 1>&2
  exit 2
fi

if xargs -P0 </dev/null 2>/dev/null 1>&2; then
  XARGS=-P0
fi

for arg; do
  (
    set -e
    if [ -d "${arg}" ]; then
      cd "${arg}"
      arg=./
    else
      dir=$(dirname "${arg}")
      arg=./$(basename "${arg}")
      cd "${dir}"
    fi
    find "${arg}" -type f -print0 \
      | xargs -0 -n1 "${XARGS}" "${SUM}" --
  )
done | sort | ${SUM} /dev/stdin | cut -d' ' -f4
