#!/bin/bash

# 2021-04-08 - After Ookla changed their license to move toward a pay-for-use speedtest service,
#              I wrote this script to replace it. This outputs the same data, parsed from CloudFlare
#                                                                    - Robbie // The Bald Nerd

if [[ ! -e /usr/local/bin/speed-cloudflare-cli ]]; then
  echo "speed-cloudflare-cli not installed."
  exit 1
fi

log="/var/log/nems/speedtest-cf.log"
log2="/var/log/nems/speedtest-ping.log"

if [[ ! -e /var/log/nems/speedtest.log ]]; then
  touch -t $(date -d "30 mins ago" +%Y%m%d%H%M.%S) /var/log/nems/speedtest.log
  chown nagios:nagios /var/log/nems/speedtest.log
fi
if [[ ! -e $log ]]; then
  touch -t $(date -d "30 mins ago" +%Y%m%d%H%M.%S) $log
  chown nagios:nagios $log
fi
if [[ ! -e $log2 ]]; then
  touch -t $(date -d "30 mins ago" +%Y%m%d%H%M.%S) $log2
  chown nagios:nagios $log2
fi

# While unlikely a user would have TWO speedtests scheduled at the same time, forcibly protect against it
running=0
for pid in $(pidof -x speedtest); do
  if [ $pid != $$ ]; then
    running=1
    # If the task got locked up for some reason, it may linger, so kill it if older than 10 minutes
    kill $(ps -eo pid,etimes,args | awk '/speedtest/ { if ($2 > 3600) print $1 }')
  fi
done

# Load from logs first, and then override if applicable
result1=$(cat ${log})
result2=$(cat ${log2})

if [ $running == 0 ]; then
  # I'm not going to speedtest more than every 2 minutes
  if [[ $(find ${log} -mmin +2) ]]; then
    result1=$(yes | /usr/local/bin/speed-cloudflare-cli | sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g')
    result2=$(ping -qc1 cloudflare.com 2>&1 | awk -F'/' 'END{ print (/^rtt/? "OK "$5" ms":"FAIL") }')
    echo $result1 | dd of=${log} > /dev/null 2> /dev/null
    echo $result2 | dd of=${log2} > /dev/null 2> /dev/null
  fi
fi

speedresult=$(echo $result1 | grep -i -E '(download speed|upload speed)')
pingresult=$(echo $result2)

resultarray=($speedresult)
pingarray=($pingresult)

ping=${pingarray[1]}
pingUOM=${pingarray[2]}

download=${resultarray[36]}
downloadUOM=${resultarray[37]}
upload=${resultarray[40]}
uploadUOM=${resultarray[41]}

result="$ping
$pingUOM
$download
$downloadUOM
$upload
$uploadUOM"

echo "${result}"
