#!/bin/bash
#
# git_wipe.sh  –  Recursively delete all Git data from a directory tree
#
#   • Deletes every “.git” directory it encounters (the repository store)
#   • Optionally deletes auxiliary Git-only files such as .gitignore, .gitmodules,
#     .gitattributes, .gitmessage, .gitkeep, etc.
#   • Dry-run mode (-n) prints what would be deleted without touching anything.
#
# USAGE
#   chmod +x git_wipe.sh
#   ./git_wipe.sh               # operate on the current directory
#   ./git_wipe.sh /path/to/dir  # operate on a specific directory
#   ./git_wipe.sh -n            # show what would be removed (dry-run)
#   ./git_wipe.sh -f /dir       # forced: delete Git aux files too
#
# EXIT STATUS
#   0  success
#   1  nothing removed / dry-run only
#   2  invalid usage

set -euo pipefail

print_help() {
  grep '^#' "$0" | sed 's/^# \{0,1\}//'
}

# --- Parse arguments ---------------------------------------------------------
DRYRUN=0
AUXFILES=0
TARGET="."

while [[ $# -gt 0 ]]; do
  case "$1" in
    -n|--dry-run) DRYRUN=1 ;;
    -f|--full)    AUXFILES=1 ;;            # remove .gitignore, etc.
    -h|--help)    print_help; exit 0 ;;
    *)            TARGET="$1" ;;
  esac
  shift
done

[[ -d "$TARGET" ]] || { echo "Error: '$TARGET' is not a directory" >&2; exit 2; }

# --- Build file list ---------------------------------------------------------
# 1. All “.git” directories (the main payload)
# 2. Optional auxiliary Git-specific files
mapfile -t GIT_DIRS < <(find "$TARGET" -type d -name '.git' -prune)

if [[ $AUXFILES -eq 1 ]]; then
  mapfile -t AUX < <(find "$TARGET" -type f \
     \( -name '.gitignore' -o -name '.gitmodules' -o -name '.gitattributes' \
        -o -name '.gitmessage' -o -name '.gitkeep' \))
  GIT_DIRS+=("${AUX[@]}")
fi

# --- Act ---------------------------------------------------------------------
if [[ ${#GIT_DIRS[@]} -eq 0 ]]; then
  echo "No Git data found under '$TARGET'."
  exit 1
fi

if [[ $DRYRUN -eq 1 ]]; then
  echo "Dry-run: would remove the following paths:"
  printf '  %s\n' "${GIT_DIRS[@]}"
  exit 1
fi

printf 'Removing %d item(s)…\n' "${#GIT_DIRS[@]}"
rm -rf -- "${GIT_DIRS[@]}"
echo "Done."