#!/bin/bash
set -e
DATA_FILE="${DATA_FILE:-/data/speedtest.csv}"
HTML_FILE="${HTML_FILE:-/usr/share/nginx/html/index.html}"
FOOTER_HTML=' '
# If no data exists yet, create a placeholder
if [ ! -f "$DATA_FILE" ] || [ ! -s "$DATA_FILE" ]; then
cat > "$HTML_FILE" << EOF
Speedtest Results
Speedtest Results
No data available yet. Please wait for the first speedtest to complete.
$FOOTER_HTML
EOF
exit 0
fi
# Count records (excluding header)
count=$(tail -n +2 "$DATA_FILE" | wc -l)
# Calculate averages using awk
stats=$(tail -n +2 "$DATA_FILE" | awk -F',' '
{
download_sum += $2;
upload_sum += $3;
ping_sum += $4;
count++
}
END {
printf "%.2f %.2f %.2f",
(count > 0 ? download_sum/count : 0),
(count > 0 ? upload_sum/count : 0),
(count > 0 ? ping_sum/count : 0)
}'
)
avg_download=$(echo "$stats" | awk '{print $1}')
avg_upload=$(echo "$stats" | awk '{print $2}')
avg_ping=$(echo "$stats" | awk '{print $3}')
# Generate JavaScript data arrays from CSV
data_js=$(tail -n +2 "$DATA_FILE" | awk -F',' '
BEGIN { print "const data = [" }
{
gsub(/"/, "\\\"", $6);
gsub(/"/, "\\\"", $7);
printf " {timestamp: \"%s\", download: %s, upload: %s, ping: %s, jitter: %s, server: \"%s (%s)\"},\n",
$1, $2, $3, $4, $5, $6, $7
}
END { print "];" }'
)
# Create HTML with embedded data and Plotly.js
cat > "$HTML_FILE" << EOF
Speedtest Results
Speedtest Results
Avg Download
${avg_download} Mbps
Avg Upload
${avg_upload} Mbps
$FOOTER_HTML
EOF
echo "Generated HTML report at $HTML_FILE"