#!/usr/bin/env sh

(
  set -o errexit
  set -o noclobber
  set -o noglob
  set -o nounset
  set -o verbose
  set -o xtrace
  # find the newest `$HISTFILE`
  # without specifying the shell
  file="$(
    command find -- "${HOME%/}" \
      -path "${HOME%/}"'/[A-Za-z0-9_-]*' -prune -o \
      -path "${HOME%/}"'/*/*' -prune -o \
      -path "${HOME%/}"'/.*history' \
      -type f \
      -exec ls -1 -t -- {} + 2>/dev/null \
      | command sed -e '1q'
  )"
  # shellcheck disable=SC2312
  # verify `$HISTFILE` exists and is not empty
  test -s "${file-}" \
    && command mkdir -p -- "${file-}"'_bak' \
    && {
      # ...and that it is not empty
      test "$(command find -- "${file-}"'_bak' -name "${file##*/}"'*' -type f)" != '' \
        || test "$(
          command find -- "${file-}" -prune -newer "$(
            # ...by comparing it to the newest file in the backup directory
            command find -- "${file-}"'_bak' \
              -path '*/.git' -prune -o \
              -type f \
              -exec ls -1 -t -- {} + 2>/dev/null \
              | command sed -e '1q'
          )"
        )" != ''
    } \
    && command cp -- "${file-}" "${file-}"'_bak/'"${file##*/}"'_'"$(command date -- '+%Y%m%d')"
)
