#!/usr/bin/env bash
#
# Computes the SHA of the content of a whole directory: SHA all the files in
# that directory and prints the SHA of the list of SHAs.
# Usage: dir_sha.sh directory_to_sha

set -euo pipefail

print_help() {
  echo "Usage: dir_sha.sh dir_to_sha"
  echo "Options:"
  echo "  -h, --help: print this help message and exit"
  echo "  --light   : computes a light version of the sha, only taking into"
  echo "              account some of the meta information about the files in"
  echo "              the directory"
}


while [[ $# -gt 0 ]]
do
key="$1"
case $key in
  -h|--help)
  print_help
  exit 0
  ;;
  --light)
  light_sha=1
  shift
  ;;
  *)
  dir_to_sha=$1
  if [ ! -d $dir_to_sha ]; then
    echo "ERROR: $dir_to_sha does not exist" >&2
    exit 1
  fi
  shift
  ;;
esac
done

if [ ! -v dir_to_sha ]; then
  echo "ERROR: missing argument dir_to_sha" >&2
  print_help >&2
  exit 1
fi

# We need to enter the directory to SHA so that the path to the directory
# itself does not contribute to the SHA.
(
  builtin cd "$dir_to_sha"
  if [ -v light_sha ]; then
    prog="du -b"
  else
    prog=sha256sum
  fi
  find -type f -print0 | xargs -0 $prog | \
   LC_ALL="POSIX" sort --key=2 | \
   sha256sum | \
   cut --delimiter=' ' --fields=1
)
