#!/bin/bash

# List a Mastodon account's follows and followers from a given server.

# This is a function so I don't have to worry about resetting $IFS
get_handle () { 
  local IFS='@'
  read -p "Enter your Mastodon handle (e. g. username@mastodon.example.com): " handle home_instance
}

get_handle

# Get instance to look up 
read -p "Show follows & followers on this server: (e. g. mastodon.example.com): " instance

# Get account ID
acct_id=$(curl -s https://"$home_instance"/api/v1/accounts/lookup?acct=$handle | jq -r '.id') 

# Initial URLs
following_url="https://$home_instance/api/v1/accounts/$acct_id/following?limit=80"
followers_url="https://$home_instance/api/v1/accounts/$acct_id/followers?limit=80"

# Output file name
output_file="${instance}-follows-followers.txt"

# Temporary file for headers
temp_headers=$(mktemp)

# Get people you follow
printf '%s\n' "People you follow on $instance:" | tee $output_file 
# All following tee's need to be tee -a
while [ -n "$following_url" ]; do 
  # Download headers to temp file; parse API results for matching accounts;
  # print to stdout and append to the output file.
  curl -s "$following_url" -D "$temp_headers" | \
  jq -r --arg instance $instance ' .[] | select(.url | contains($instance)) | .acct' | \
  tee -a $output_file
  # Search headers for link to next page of results
  following_url=$(grep -Po '(?<=link\: \<).+(?=\>\; rel\=\"next\")' "$temp_headers")
done

# Get followers
printf '\n%s\n' "Your followers on $instance:" | tee -a $output_file
while [ -n "$followers_url" ] ; do 
  curl -s "$followers_url" -D "$temp_headers" | \
  jq -r --arg instance $instance ' .[] | select(.url | contains($instance)) | .acct' | \
  tee -a $output_file
  followers_url=$(grep -Po '(?<=link\: \<).+(?=\>\; rel\=\"next\")' "$temp_headers")
done

# Delete temporary headers file
rm "$temp_headers"

printf '\n%s\n' "Done! Output saved at: $(realpath $output_file)"

# ---------
# Output options:
# .username: "user" (no @, no instance)
# .acct: "user@mastodon.example.com" (note: if @ prepended, i. e. '"@" + .acct', 
#   will be mentioned if data is posted into mentions-only posts; 
#   possibly undesirable)
# .url: "https://mastodon.example.com/@user" 
# Can combine fields with + (e. g. '.acct + "\t" + .url), or make a whole new 
#   json thingy, or whatever you like. See jq documentation for more details. 
