#!/bin/sh
# Given a list of file names as arguments, print the ones with unique
# contents: for each group of files with identical contents, only the
# first one (in argument order) is printed.
#
# Every argument that is not printed is reported on stderr; the other files
# are still processed.  Exits with status 1 if an argument does not exist or
# could not be read.  An argument that exists but is not a regular file (a
# directory, most often) is only warned about, because `uniq-contents *` in a
# directory that contains a subdirectory is an ordinary invocation, not an
# error, and a nonzero status would abort a caller that uses `set -e`.

# Pick a hashing command; sha256 makes accidental collisions
# (calling distinct files identical) astronomically unlikely.
if command -v sha256sum >/dev/null 2>&1; then
  hash_cmd="sha256sum"
elif command -v shasum >/dev/null 2>&1; then
  hash_cmd="shasum -a 256"
else
  hash_cmd="cksum"
fi

prog=$(basename -- "$0")

status=0
seen=""
for f in "$@"; do
  # Report, rather than silently skip, anything that is not a regular file:
  # dropping a file from the output without a diagnostic is the same silent
  # data loss as mishandling an unreadable one.  Use `printf`, not `echo`:
  # `echo` interprets backslashes in a file name in some shells.
  if [ ! -e "$f" ]; then
    printf '%s: no such file: %s\n' "$prog" "$f" >&2
    status=1
    continue
  fi
  # Not an error; see the comment at the top of this file.
  if [ ! -f "$f" ]; then
    printf '%s: warning: not a regular file: %s\n' "$prog" "$f" >&2
    continue
  fi

  # Do not pipe into `cut`:  `sh` has no `pipefail`, so the status of the
  # hashing command would be lost and an unreadable file would silently
  # produce an empty hash.  An empty hash is recorded as seen, after which
  # every unreadable file -- including the first one -- looks like a
  # duplicate.  The `2>/dev/null` precedes the input redirection so that it
  # also suppresses the shell's own "cannot open" message.
  if ! sum=$($hash_cmd 2>/dev/null < "$f"); then
    printf '%s: cannot read %s\n' "$prog" "$f" >&2
    status=1
    continue
  fi
  # Discard everything after the hash itself (a file name or a byte count).
  sum=${sum%% *}

  case " $seen " in
    *" $sum "*) ;;             # content already seen; skip it
    *) seen="$seen $sum"; printf '%s\n' "$f" ;;
  esac
done

exit "$status"
