#!/bin/bash

if [ -z "$1" ]; then
  echo "Usage: $0 <path_to_accounts.json>"
  exit 1
fi

ACCOUNTS_FILE="$1"
OUTPUT_DIR="$(pwd)/github_repo_scanners/contributor_repos"

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Run the main script and capture its output
FULL_OUTPUT=$(./github_repo_scanners/create_contributor_repo_lists.sh "$ACCOUNTS_FILE")

# Parse the output and create individual JSON files
in_json=0
contributor=""
file_content=""

echo "$FULL_OUTPUT" | while IFS= read -r line; do
  if [[ "$line" =~ ^START_JSON: ]]; then
    contributor=$(echo "$line" | sed 's/^START_JSON://')
    file_content=""
    in_json=1
  elif [[ "$line" =~ ^END_JSON: ]]; then
    echo "$file_content" > "$OUTPUT_DIR/${contributor}.json"
    in_json=0
  elif [ "$in_json" -eq 1 ]; then
    file_content+="$line\n"
  fi
done

echo "Contributor repository lists have been created in the '$OUTPUT_DIR' directory."