#!/bin/sh
#
# git-rgrep - search a repo (optionally) with (nested) submodules
#
# This works by taking the PWD, and combining that with the relative submodule
# path. This is necessary to get the relative file system path correct.
# It also outputs the format expected by vim.
#
# for use in vim: set grepprg=git\ rgrep

base_dir="${PWD}"
# search="${1//\"/\\\"}"
search="$(echo "$1" | sed 's/\"/\\"/g')"
search_dir="${2:-*}"

if [ -z "${search}" ]; then
  printf '%s\n' "Usage: git rgrep [query] [subdirectory]" 2>&1
  exit 1
fi

git --no-pager grep -n "${search}" "${search_dir}"
# shellcheck disable=SC2250
git --no-pager submodule foreach --recursive --quiet "
  nested_dir=\$(git rev-parse --show-toplevel)
  relative_dir=\$(echo \$nested_dir | sed s=^$base_dir/==)
  git grep -n \"$search\" | while read line; do echo \$relative_dir/\$line; done
"
