#!/bin/sh -e
#
# newest - list newest files in specified paths and by default any subdirs
# if no paths are specified, current directory is listed
#
# note:
#   - this script explicitly ignores repository metadata
#   - this script (well find actually) fails for user specified paths,
#     that begin with '-', '(' or '!', so prepend './' for paths like that
#
# ---
# source: https://github.com/pixelb/scripts

num="20"

usage() {
  printf %s "\
$(basename "$0")
  is a simple script to list the newest files in the specified paths

usage:
  $(basename "$0") [-nr] [-na] [-n#] [-s] [-r] [path...]

options:
  -h, --help    - Display this message
  -nr           - Do not recurse
  -na           - Ignore files starting with '.'
  -n#           - List the newest <files> (Default: ${num})
  -r            - Reverse to show oldest files
"
  exit 1
}

if command -v gfind >/dev/null 2>&1; then
  find() (
    gfind "$@"
  )
fi

num="-n${num}"
dotfiles="yes"
recurse="yes"
reverse=""
while :; do
  case "$1" in
    --)
      shift
      break
      ;;
    -na)
      dotfiles="no"
      ;;
    -nr)
      recurse="no"
      ;;
    -n[0-9]*)
      num=$1
      ;;
    -r)
      reverse="r"
      ;;
    -h | --help)
      usage
      ;;
    *)
      break
      ;;
  esac
  shift
done

[ "${dotfiles}" = "no" ] && ignore_hidden="-name '.*' -o"
[ "${recurse}" = "no" ] && dont_recurse="-maxdepth 1"

if [ "$#" -gt 0 ]; then
  path_format="%p"
else
  path_format="%P"
  set -- "./"
fi

ignore_metadata="\( -type d -a \( -name '.git' -o -name '.svn' -o -name 'CVS' \) \) -prune -o"
print_format="\( -type f -printf '%T@\t${path_format}\n' \)"

eval find '"$@"' "${dont_recurse}" "${ignore_metadata}" \
  "${ignore_hidden}" "${print_format}" \
  | sort -k1,1"${reverse}"n \
  | tail "${num}" \
  | cut -f2- \
  | if [ ! -p /proc/self/fd/1 ]; then
    tr '\n' '\0' | xargs -r0 ls -lUd --color=auto --
  else
    cat
  fi
