#!/bin/sh

RAW_DATA=/var/www/data/speed/raw.speedtest.json
TMP_DATA=/tmp/speedtest.js
WEB_DATA=/var/www/data/speed/speedtest.js
WEB_SHORT_DATA=/var/www/data/speed/speedtest.short.js

/usr/bin/speedtest --format=json --accept-license >> ${RAW_DATA} 2>/dev/null || speedtest --format=json --accept-license >> ${RAW_DATA} 2>/dev/null

# Prepare information for web display
tail -500 ${RAW_DATA} > ${TMP_DATA} && \
   sed -i -e 's/$/,/' ${TMP_DATA} && \
   echo "var speeddata = [" > ${WEB_DATA} && \
   cat ${TMP_DATA} >> ${WEB_DATA} && \
   echo "];" >> ${WEB_DATA}
# Prepare short information for quick web display
tail -6 ${RAW_DATA} > ${TMP_DATA} && \
   sed -i -e 's/$/,/' ${TMP_DATA} && \
   echo "var speeddata = [" > ${WEB_SHORT_DATA} && \
   cat ${TMP_DATA} >> ${WEB_SHORT_DATA} && \
   echo "];" >> ${WEB_SHORT_DATA}

# Trim raw data to keep it lean
tail -1000 ${RAW_DATA} > ${TMP_DATA} && \
    cp ${TMP_DATA} ${RAW_DATA}

echo "[$(date)] Updated speed data"

# Above arguments produce the following output in single line. Expanded for readability below:
#
# {
#   "type":"result",
#   "timestamp":"2023-04-24T03:57:04Z",
#   "ping":{
#     "jitter":0.193,
#     "latency":1.751,
#     "low":1.530,
#     "high":1.982
#   },
#   "download":{
#     "bandwidth":85545427,
#     "bytes":1017170768,
#     "elapsed":12616,
#     "latency":{
#       "iqm":1.894,
#       "low":1.374,
#       "high":2.916,
#       "jitter":0.300
#     }
#   },
#   "upload":{
#     "bandwidth":91982628,
#     "bytes":331336109,
#     "elapsed":3601,
#     "latency":{
#       "iqm":4.135,
#       "low":2.281,
#       "high":5.322,
#       "jitter":0.498
#     }
#   },
#   "packetLoss":0,
#   "isp":"GigaMonster",
#   "interface":{
#     "internalIp":"192.168.1.200",
#     "name":"eno1",
#     "macAddr":"B8:AE:ED:7D:8A:36",
#     "isVpn":false,
#     "externalIp":"24.72.150.52"
#   },
#   "server":{
#     "id":36565,
#     "host":"speedpdx2.ortelco.net",
#     "port":8080,
#     "name":"OTC Connections",
#     "location":"Portland, OR",
#     "country":"United States",
#     "ip":"38.87.96.27"},
#   "result":{
#     "id":"9b547022-8e1b-42c5-871c-2b6810b641bb",
#     "url":"https://www.speedtest.net/result/c/9b547022-8e1b-42c5-871c-2b6810b641bb",
#     "persisted":true
#   }
# }
