#!/bin/bash

# Check if GITHUB_USER_NAME is provided
if [ -z "$1" ]; then
  echo "Usage: $0 <GITHUB_USER_NAME>"
  exit 1
fi

GITHUB_USER_NAME="$1"
ACCOUNTS_FILE="accounts.json"

# Check if accounts.json exists
if [ ! -f "$ACCOUNTS_FILE" ]; then
  echo "Error: $ACCOUNTS_FILE not found."
  exit 1
fi

# Loop through each account in accounts.json
jq -c '.[]' "$ACCOUNTS_FILE" | while read -r account; do
  USER=$(echo "$account" | jq -r '.user')
  TOKEN=$(echo "$account" | jq -r '.token')

  echo "Scanning repos for account: $USER"

  # Get all repos for the user
  REPOS=$(curl -s -H "Authorization: token $TOKEN" "https://api.github.com/user/repos?type=all&per_page=100" | jq -r '.[].full_name')

  for REPO in $REPOS; do
    # Get collaborators for each repo
    COLLABORATORS=$(curl -s -H "Authorization: token $TOKEN" "https://api.github.com/repos/$REPO/collaborators" | jq -r '.[].login')
    if echo "$COLLABORATORS" | grep -q "$GITHUB_USER_NAME"; then
      echo "  - $GITHUB_USER_NAME has access to $REPO"
    fi
  done
done
