#!/usr/bin/env bash
# Adapted from the one-liner at https://news.ycombinator.com/item?id=12259331
set -eu -o pipefail

if ! command -v pv >/dev/null; then
    echo >&2 "Pipe viewer, pv, is required. Please install pv with your package manager."
    exit 1
fi

if ! command -v jq >/dev/null; then
    echo >&2 "JSON processor, jq, is required. Please install jq with your package manager."
    exit 1
fi

# Use the fifo as a lock so only one instance of this script can run. (Alternative to flock(1))
declare -r FIFO=${TMPDIR:-/tmp}/$(basename "$BASH_SOURCE").fifo
if [ -e "$FIFO" ]; then
    echo >&2 "Run aborted since fifo and mutex lock $FIFO already exists."
    exit 1
fi
mkfifo $FIFO
trap "rm -f $FIFO" EXIT

# This works on OS X, but GNU grep works without the cut: grep -Po '(?<=\<script src=")[^"]+'
declare -r JS=$(curl -s https://fast.com/ | egrep -o '\<script src="[^"]+' | cut -f2 -d'"')
# This works on OS X, but GNU grep works without the cut: grep -Pom1 '(?<=token:")[^"]+'
declare -r TOKEN=$(curl -s https://fast.com/$JS | egrep -om1 'token:"[^"]+' | cut -f2 -d'"')

echo "# Bytes Cur. rate   Avg. Rate"
echo "------- ----------- -----------"

# Get a list of URL templates, insert ranges, and make requests in the background.
curl -s "https://api.fast.com/netflix/speedtest?https=true&token=$TOKEN" | jq -r '.[].url' | while read url
do
    FILE_2K=${url/speedtest/speedtest\/range\/0-2048}
    FILE_25M=${url/speedtest/speedtest\/range\/0-26214400}
    (curl -s -H 'Referer: https://fast.com/' -H 'Origin: https://fast.com' "$FILE_2K" > $FIFO
     for i in {1..10}
     do
         curl -s -H 'Referer: https://fast.com/' -H 'Origin: https://fast.com'  "$FILE_25M" > $FIFO
     done) &
done
pv -rab $FIFO > /dev/null