#!/usr/bin/env bash

find-git-folder() {
    if [[ -z "$1" ]]; then
        echo '$1/path is empty.'
        exit
    fi
    [[ ! -d "$1" ]] && { echo "Error: '$1' is not a directory." >&2; return 1; }

    local excludes="${GIT_FOLDER_EXCLUDE:-.cache,node_modules,venv,__pycache__,.vim,.fzf,.password-store,.oh-my-zsh}"
    local find_cmd="find \"$1\" -maxdepth 3"

    IFS=',' read -ra patterns <<< "$excludes"
    for pattern in "${patterns[@]}"; do
        pattern=$(echo "$pattern" | xargs)
        [[ -n "$pattern" ]] && find_cmd="$find_cmd \( -name '$pattern' -o -path \"*/$pattern/*\" \) -prune -o"
    done

    find_cmd="$find_cmd -type d -name '.git' -print"

    eval "$find_cmd" 2>/dev/null | while IFS= read -r git_dir; do
        [[ "$git_dir" != "./.git" ]] && dirname "$git_dir"
    done
}
fgf() {
    find-git-folder "$@"
}
