#!/bin/bash

# list_teams_and_members.sh: List all teams and their members for a GitHub organization
# Usage: ./list_teams_and_members.sh --org <orgname>

set -e

RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
RESET=$(tput sgr0)

if ! command -v jq &>/dev/null; then
    echo "${RED}❌ Error: 'jq' is required but not installed.${RESET}"
    exit 1
fi

if [[ -z "$GITHUB_TOKEN" ]]; then
    echo "${RED}❌ GITHUB_TOKEN is not set in your environment.${RESET}"
    exit 1
fi

echo "${BLUE}Fetching organizations for the authenticated user...${RESET}"
ORGS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/user/orgs" | jq -r '.[].login')

if [[ -z "$ORGS" ]]; then
    echo "${YELLOW}No organizations found for this user.${RESET}"
    exit 0
fi

for ORG in $ORGS; do
    echo -e "${GREEN}Organization: $ORG${RESET}"
    TEAMS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/orgs/$ORG/teams" | jq -r '.[].slug')
    if [[ -z "$TEAMS" ]]; then
        echo "  ${YELLOW}No teams found in $ORG${RESET}"
        continue
    fi
    for TEAM in $TEAMS; do
        echo "  ${BLUE}Team: $TEAM${RESET}"
        MEMBERS=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "https://api.github.com/orgs/$ORG/teams/$TEAM/members" | jq -r '.[].login')
        if [[ -z "$MEMBERS" ]]; then
            echo "    ${YELLOW}No members found in $TEAM${RESET}"
            continue
        fi
        for MEMBER in $MEMBERS; do
            echo "    Member: $MEMBER"
        done
    done
done 