#!/usr/bin/env bash
set -Eeuo pipefail

# Git mantenimiento para un worktree
# - git fetch --all --prune
# - git remote prune origin
# - git gc --aggressive --prune=now

usage(){
  cat << EOF
Uso: $(basename "$0") [-y] [-s] -w <worktree>
  -w <worktree>  Directorio del repositorio a mantener
  -y             No interactivo
  -s             Forzar uso de sudo (por defecto no)
EOF
}

NON_INTERACTIVE=0
WORKTREE=""
USE_SUDO=0
while getopts ":w:ysh" opt; do
  case $opt in
    w) WORKTREE="$OPTARG" ;;
    y) NON_INTERACTIVE=1 ;;
    s) USE_SUDO=1 ;;
    h) usage; exit 0 ;;
    *) usage; exit 1 ;;
  esac
done

if [[ -z "$WORKTREE" ]]; then
  usage; echo "Falta -w <worktree>" >&2; exit 1
fi

if [[ ! -d "$WORKTREE/.git" ]]; then
  echo "❌ No es un repositorio Git: $WORKTREE" >&2
  exit 1
fi

pushd "$WORKTREE" >/dev/null
echo "📦 Mantenimiento Git en: $WORKTREE"
if [[ "$USE_SUDO" == "1" ]]; then SUDO=sudo; else SUDO=""; fi
GIT_CMD=(git -c safe.directory="$WORKTREE")
if [[ -n "$SUDO" ]]; then GIT_CMD=(sudo git -c safe.directory="$WORKTREE"); fi
"${GIT_CMD[@]}" fetch --all --prune
"${GIT_CMD[@]}" remote prune origin || true
"${GIT_CMD[@]}" gc --aggressive --prune=now
echo "✅ Mantenimiento completado"
popd >/dev/null

exit 0
