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

# ---- Config: set these at the top ----
GITEA_BASE="https://git.keithsolomon.net"
GITEA_USER="keith"
GITEA_TOKEN="f4b01fa50f56271f8ba002221fb68404de955077"
REMOTE_NAME="origin"                 # which remote to use/push
SEARCH_ROOT="${1:-$PWD}"             # default to current dir if not provided

# sanity checks
command -v jq >/dev/null 2>&1 || { echo "jq is required. Install with: sudo apt install jq"; exit 1; }

: "${GITEA_BASE:?Need GITEA_BASE}"
: "${GITEA_USER:?Need GITEA_USER}"
: "${GITEA_TOKEN:?Need GITEA_TOKEN}"

SEARCH_ROOT="$(realpath "$SEARCH_ROOT")"

echo "Scanning for git repos under: $SEARCH_ROOT"
echo

# Use -print0 to safely handle spaces/newlines in paths
find "$SEARCH_ROOT" -type d -name ".git" -print0 | while IFS= read -r -d '' gitdir; do
  # Absolute repo dir
  repo_dir="$(dirname "$gitdir")"
  repo_dir="$(realpath "$repo_dir")"

  echo "=== $repo_dir ==="

  # Run everything for this repo in a subshell so cd doesn't affect the outer loop
  (
    cd "$repo_dir" || exit 0

    # Get origin URL (or skip if none)
    if ! url=$(git remote get-url "$REMOTE_NAME" 2>/dev/null); then
      echo "  -> Skipping (no '$REMOTE_NAME' remote)"
      exit 0
    fi

    # Only migrate repos that point (or pointed) at git.keithsolomon.net
    if [[ "$url" != *"git.keithsolomon.net"* ]]; then
      echo "  -> Skipping (origin is not git.keithsolomon.net)"
      exit 0
    fi

    # Derive repo name: strip .git and take basename
    clean_url="${url%.git}"
    repo_name="$(basename "$clean_url")"

    echo "  -> Repo name on Gitea: $repo_name"

    # Create repo via Gitea API (idempotent: 201 = created, 409 = already exists)
    create_payload=$(jq -n \
      --arg name "$repo_name" \
      --arg desc "Imported from local clone at $repo_dir" \
      '{name: $name, private: true, description: $desc}')

    http_status=$(
      curl -sS -o /tmp/gitea-create-repo.out \
        -w "%{http_code}" \
        -X POST "$GITEA_BASE/api/v1/user/repos" \
        -H "Content-Type: application/json" \
        -H "Authorization: token $GITEA_TOKEN" \
        -d "$create_payload" || echo "000"
    )

    if [[ "$http_status" == "201" ]]; then
      echo "  -> Created repo on Gitea"
    elif [[ "$http_status" == "409" ]]; then
      echo "  -> Repo already exists on Gitea, continuing"
    else
      echo "  !! Unexpected HTTP status $http_status creating repo, output:"
      cat /tmp/gitea-create-repo.out
      echo "  !! Skipping push for $repo_dir"
      echo
      exit 0
    fi

    # Make sure origin URL points at the new Gitea HTTPS remote
    new_url="$GITEA_BASE/$GITEA_USER/$repo_name.git"
    git remote set-url "$REMOTE_NAME" "$new_url" 2>/dev/null || git remote add "$REMOTE_NAME" "$new_url"

    echo "  -> Pushing all branches..."
    git push --all "$REMOTE_NAME" || echo "  !! Failed pushing branches"
    echo "  -> Pushing tags..."
    git push --tags "$REMOTE_NAME" || echo "  !! Failed pushing tags"
    echo
  )
done

echo "Done."
