#!/usr/bin/env sh
# A wrapper to parallelize grep and optionally filter by filename pattern
#
# Usage
#
# `glr [<flags>] searchterm [<searchpath> | (<grep args>...)]`
#
#     glr -h
#     glr searchterm
#     glr searchterm /search/path
#     glr -t 'name ~~ "*.js"' searchterm ./searchpath
#     glr searchterm file1 file2 file3
#
# Flag | Description
# ---- | -----------
# -I   | Force case-sensitve search.
# -E   | Use extended regular expression search
# -V   | Show version.
# -X   | Shorthand for adding a test condition for a file extension.
# -h   | Usage and help text.
# -p   | Do not open search results in a pager.
# -t   | Pass additional test conditions to lr; multiple occurences ok.
# -x   | Enable xtrace debug logging.
#
# Flags _must_ be the first argument to `glr`, before `searchterm`.
#
# Search will be case-sensitive if the search text contains capital
# letters.
#
# If given no search path, a single search path, or specific search paths
# via `-T` this wrapper will use flr to generate the list of files and
# parallelize grep using xe.
#
# Automatically parallelized:
#
#     glr searchterm
#     glr searchterm ./searchpath
#     glr -t 'name ~~~ "*.js"' searchterm
#     glr -t 'size > 1M' -t 'mode | 700' searchterm
#     glr -X js searchterm
#
# If given one or more file names to search it will instead behave like
# regular grep and flr will not be invoked.

version="1.1.0"

NAME=$(basename "$0")
TEMP="${TMPDIR-/tmp}/${NAME}.${$}.$(awk \
  'BEGIN { srand(); printf "%d\n", rand() * 10^10 }')"
EXIT="${TEMP}/exit"

# shellcheck disable=SC2154
trap '
  excode=$?; trap - EXIT;
  rm -rf -- '"${TEMP}"'
  exit $excode
' INT TERM EXIT

# shellcheck disable=SC2220
while getopts 'hVxt:X:pIE' opt; do
  case "${opt}" in
    h)
      awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
      exit 0
      ;;
    V)
      printf '%s\n' "${0##*/} ${version}"
      exit 0
      ;;
    x)
      PS4='[${LINENO}]+ '
      set -x
      ;;
    t)
      if [ -n "${testcond}" ]; then
        testcond="${testcond} && ${OPTARG}"
      else
        testcond="${OPTARG}"
      fi
      ;;
    X)
      # shellcheck disable=SC2089
      exttest="name ~~~ \"*.${OPTARG}\""
      if [ -n "${testcond}" ]; then
        testcond="${testcond} && ${exttest}"
      else
        testcond="${exttest}"
      fi
      ;;
    p) nopager=1 ;;
    I) casesensitive=1 ;;
    E) extregex=1 ;;
    # *)
    #   printf '%s: Unrecognized option: -- %s\n' "$(basename "$0")" "$1" >&2
    #   exit 1
    #   ;;
  esac
done
shift "$((OPTIND - 1))"

mkdir -m 700 "${TEMP}"
# shellcheck disable=SC2181
if [ "$?" -ne 0 ]; then
  printf 'Error creating temp directory.\n' 1>&2
  exit 1
fi

if [ -t 1 ] && [ -z "${nopager}" ]; then
  usepager=1
fi

search="${1:?'Missing "search term".'}"
shift

# Check for capital letters in the search pattern.
if [ -z "${casesensitive}" ]; then
  if ! printf '%s\n' "${search}" | grep -q -E '[A-Z]' 2>/dev/null; then
    is_icase=1
  fi
fi

# If we're given a search path use find to generate list of files to
# search, otherwise assume the file list is provided and just pass to grep.
if [ "$#" -eq 0 ]; then
  searchpath='.'
else
  if [ -d "$1" ]; then
    searchpath="$1"
    shift
  fi
fi

{
  if [ -n "${searchpath}" ]; then
    # shellcheck disable=SC2090
    flr -0 -t 'type == f' ${testcond:+-t "${testcond}"} "${searchpath}" \
      | xe -0 -j0 -N0 -L \
        grep --color"${usepager:+=always}" ${is_icase:+-i} ${extregex:+-E} -nH -e "${search}" "$@"
    printf '%s\n' $? >"${EXIT}"
  else
    grep --color"${usepager:+=always}" ${is_icase:+-i} ${extregex:+-E} -nH -e "${search}" "$@"
    printf '%s\n' $? >"${EXIT}"
  fi
} | {
  if [ -n "${usepager}" ]; then
    ${PAGER:-less} -FR
  else
    cat
  fi
}

# Only way to retain the grep exit code since we use a pager.
read -r ret <"${EXIT}"
exit "${ret}"
