#!/usr/bin/env bash
#
## Requires jq
#
## Example: bash github-api-contributors-gen.sh "danielmiessler/SecLists"
#

## https://github.com/<value>
githubRepo=${1:-danielmiessler/SecLists}

## How many avatar's per row
avatar_row=5

## Start at the start
page=1

## Empty the values
login=()
avatar_url=()
url=()

## Do until there isn't anything returned
while true; do
  ## Call the API, to extract the JSON for that page
  json=$( curl -s "https://api.github.com/repos/${githubRepo}/contributors?page=${page}" )

  ## Check to see if its empty or not - if it is, exit the loop
  [[ -z "$( echo ${json} | jq -r '.[]' )" ]] \
    && break

  ## Loop over all three values, save to an array (dirty - as multiple loops hardcoded...)
  for x in $( echo ${json} | jq -r ".[].login" ); do
    login+=($x)
  done

  for x in $( echo ${json} | jq -r ".[].avatar_url" ); do
    avatar_url+=($x)
  done

  for x in $( echo ${json} | jq -r ".[].url" ); do
    url+=($x)
  done

  ## Check to make sure all arrays are the same length (dirty - but works...)
  if [ "${#login[@]}" -ne "${#avatar_url[@]}" ]; then
    echo "[-] Issues with login & avatar_url"
    exit 1
  elif [ "${#login[@]}" -ne "${#url[@]}" ]; then
    echo "[-] Issues with login & url"
    exit 1
  fi

  ## Increase the page count
  (( page ++))
done


## Make markdown headers
for x in "   " "---"; do
  echo -n "|"
  for y in $( seq 1 "${avatar_row}" ); do
    echo -n "${x}|"
  done
  echo
done


## Counter for avatar_row
i=1
## For every value in the arrays above, do the following
for x in $( seq 0 "${#login[@]}" ); do
  ## As array starts at 0, length starts at 1, there will be one extra - skip the end!
  [ ${x} -eq ${#login[@]} ] \
    && break

  echo -n "<img width='50' src='${avatar_url[${x}]}'/><br />[${login[${x}]}](${url[${x}]}) | "

  ## Every x rows, do put onto a new line
  [ $i -ge ${avatar_row} ] \
    && i=0 \
    && echo

  ## Increase the row count
  (( i ++))
done
echo
