#!/bin/sh -e
#
# git find-repos [DIRS] - list all git repos below DIRS (or current directory)
#
# Find Git repos under CWD, and optionally run a Git command in each
#
#     git find-repos
#     git find-repos -0
#     git find-repos rev-parse --symbolic-full-name @


# find "${@:-.}" -name HEAD -execdir sh -c \
#   'git rev-parse --resolve-git-dir . >/dev/null 2>/dev/null && pwd' ';'

sep='\n'
# shellcheck disable=SC2249
while getopts ':hx0' opt; do
  case "${opt}" in
    h)
      awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
      exit 0
      ;;
    0)
      sep='\0'
      ;;
    x)
      set -x
      ;;
    ?)
      printf '%s: Invalid option -- %s\n' "${0##*/}" "$1" >&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

if [ "$#" -gt 0 ]; then
  has_cmd=1
  sep='\0'
else
  has_cmd=0
fi

# shellcheck disable=SC2016,SC2250
lr -0Ut 'name == "HEAD"' | xe -0 -s 'd=${1%/*}
    test -O "$d"/refs -a -O "$d"/objects && printf "%s'"$sep"'" "$d"' | {
  if [ "${has_cmd}" -eq 1 ]; then
    xe -0 -j5 -s 'git --git-dir="$1" '"$*"
  else
    cat
  fi
}
