#!/bin/sh

set -e

CRON_MINUTE=${CRON_MINUTE:-10}
PORT=${PORT:-8080}

# Ensure data directory exists
mkdir -p /var/www/data/speed

# Ensure raw data file exists
touch /var/www/data/speed/raw.speedtest.json

# If the data directory is a mounted volume it may be owned by root; allow writes
# by ensuring the directory is writable.
chown -R root:root /var/www/data || true
chmod -R a+rwX /var/www/data || true

# Ensure the cron job exists in Cron
CRON_FILE=/etc/cron.d/speedtest-cron
if [ -f ${CRON_FILE} ] && grep run_speed_test ${CRON_FILE}; then
    echo "cron entry already present"
else
    echo ${CRON_MINUTE} '* * * * root /usr/local/bin/run_speed_test.sh >> /var/log/cron.log 2>&1' > ${CRON_FILE}
fi

# Start Debian cron in background
service cron start || cron || true

# Run the initial speed test once (in background) to populate files if possible
# We run it in background so server starts promptly. The cron will run hourly.
/usr/local/bin/run_speed_test.sh >> /var/log/cron.log 2>&1 || true &

# Start busybox httpd serving /var/www on configured port in foreground
if command -v busybox >/dev/null 2>&1; then
    echo "starting busybox httpd on port ${PORT} serving /var/www"
    busybox httpd -f -p ${PORT} -h /var/www
else
    echo "warning: busybox httpd not found; container will keep running with cron only" >&2
    # keep the script running so container doesn't exit
    tail -f /var/log/cron.log
fi
