#!/bin/bash
set -euo pipefail

INTERACTIVE=true
for arg in "$@"; do
  case "$arg" in
    --help|-h)
      cat <<'EOF'
Usage: checkin-all [options]

Check git status for all repos matching *schmeeve* in ~/git/,
and interactively prompt to commit & push changes.

Options:
  -n, --no-interactive    Auto-commit changes with timestamp message
  -h, --help              Show this help message and exit
EOF
      exit 0
      ;;
    --no-interactive|-n) INTERACTIVE=false ;;
  esac
done

GIT_HOME="${HOME}/git"

for dir in "${GIT_HOME}"/*/ "${HOME}/Dotfiles"; do
  if [ -d "${dir}/.git" ]; then
    repo=$(basename "${dir}")
    remote=$(git -C "${dir}" remote get-url origin 2>/dev/null || true)
    case "${remote}" in
      *schmeeve*)
        ;;
      *)
        echo "  Skipping (not your repo: ${remote})"
        continue
        ;;
    esac
    echo "=== ${repo} ==="
    cd "${dir}"
    if [ -n "$(git status --porcelain 2>/dev/null)" ]; then
      if $INTERACTIVE; then
        git status --short
        echo ""
        read -r -p "  Commit message (empty = skip): " msg
        if [ -z "$msg" ]; then
          echo "  Skipped."
        else
          git add -A
          git commit -m "$msg"
          git push
        fi
      else
        echo "  Changes found → committing and pushing..."
        git commit -a -m "auto: $(date '+%Y-%m-%d %H:%M')" || echo "  Nothing to commit (maybe no tracked files changed)"
        git push
      fi
    else
      echo "  Clean."
    fi
  fi
done
