#!/usr/bin/env bash
#
# migrate-github-org.sh
#
# Scans a workspace directory for git repos and repoints any remote that
# points at OLD_ORG on github.com to NEW_ORG, keeping the repo name and
# the HTTPS protocol (what GitHub Desktop uses) unchanged.
#
# Usage:
#   ./migrate-github-org.sh [workspace-dir]
#
#   workspace-dir defaults to the current directory.
#
# Safe to re-run: repos already pointing at NEW_ORG, or at any org other
# than OLD_ORG, are left untouched and reported as skipped.

set -euo pipefail

OLD_ORG="agilantsolutions"
NEW_ORG="togatech"

WORKSPACE="${1:-.}"

if [ ! -d "$WORKSPACE" ]; then
    echo "Error: workspace directory not found: $WORKSPACE" >&2
    exit 1
fi

updated=0
skipped=0
not_git=0

echo "Scanning $WORKSPACE for git repositories..."
echo "Renaming remotes: github.com/$OLD_ORG/<repo> -> github.com/$NEW_ORG/<repo>"
echo

# Only descend one level into WORKSPACE — each subfolder is treated as a
# candidate repo. Adjust maxdepth if your repos are nested deeper.
while IFS= read -r -d '' gitdir; do
    repo_path="$(dirname "$gitdir")"
    repo_name="$(basename "$repo_path")"

    remote_url="$(git -C "$repo_path" remote get-url origin 2>/dev/null || true)"

    if [ -z "$remote_url" ]; then
        echo "  [no origin]  $repo_name"
        not_git=$((not_git + 1))
        continue
    fi

    case "$remote_url" in
        *"github.com/$OLD_ORG/"*|*"github.com:$OLD_ORG/"*)
            new_url="${remote_url/$OLD_ORG/$NEW_ORG}"
            git -C "$repo_path" remote set-url origin "$new_url"
            echo "  [updated]    $repo_name"
            echo "               $remote_url"
            echo "            -> $new_url"
            updated=$((updated + 1))
            ;;
        *)
            echo "  [skipped]    $repo_name  ($remote_url)"
            skipped=$((skipped + 1))
            ;;
    esac
done < <(find "$WORKSPACE" -mindepth 2 -maxdepth 2 -type d -name ".git" -print0)

echo
echo "Done. Updated: $updated, skipped (not $OLD_ORG): $skipped, no origin: $not_git"

if [ "$updated" -gt 0 ]; then
    echo
    echo "Next steps for each updated repo:"
    echo "  - If you use GitHub Desktop, close and reopen the repo (or restart Desktop)"
    echo "    so it picks up the new remote URL."
    echo "  - The first push/pull against the new org may prompt you to re-authenticate"
    echo "    if your GitHub account/token doesn't already have access to $NEW_ORG."
fi
