#!/bin/sh
# speedtest_ex600.sh - Speed test periodico para Genexis EX600 (GenXOS/IOPSYS, OpenWrt 21.02)
# Compatible con BusyBox ash. Mide latencia, descarga y subida contra Cloudflare
# y registra en CSV para analizar estabilidad en el tiempo.
#
# Uso:      sh speedtest_ex600.sh          (una medicion)
#           sh speedtest_ex600.sh test     (verifica dependencias)
# Cron:     */30 * * * * /root/speedtest_ex600.sh >/dev/null 2>&1

# ---------- Configuracion ----------
LOG_FILE="/root/speedtest_log.csv"   # /root sobrevive reinicios; /tmp no
DL_BYTES=50000000                    # 50 MB de descarga (~2-10s en 40-300 Mbps)
UL_MB=15                             # 15 MB de subida
MAX_TIME=30                          # timeout por prueba (s)
MAX_LINES=3000                       # rotacion del log (~2 meses cada 30 min)
PING_HOST="1.1.1.1"
DL_URL="https://speed.cloudflare.com/__down?bytes=${DL_BYTES}"
UL_URL="https://speed.cloudflare.com/__up"
# -----------------------------------

command -v curl >/dev/null 2>&1 || { echo "ERROR: curl no esta disponible en este firmware"; exit 1; }

if [ "$1" = "test" ]; then
    echo "curl: $(curl --version | head -1)"
    ping -c1 -W2 "$PING_HOST" >/dev/null 2>&1 && echo "ping: OK" || echo "ping: FALLO"
    echo "Log: $LOG_FILE"
    exit 0
fi

TS=$(date '+%Y-%m-%d %H:%M:%S')

# --- Latencia y jitter (5 pings) ---
PING_OUT=$(ping -c5 -W2 "$PING_HOST" 2>/dev/null | tail -1)
# formato busybox: round-trip min/avg/max = 9.1/10.2/12.3 ms
LAT_AVG=$(echo "$PING_OUT" | awk -F'=' '{print $2}' | awk -F'/' '{print $2}')
LAT_MAX=$(echo "$PING_OUT" | awk -F'=' '{print $2}' | awk -F'/' '{print $3}' | awk '{print $1}')
[ -z "$LAT_AVG" ] && LAT_AVG="ERR" && LAT_MAX="ERR"

# --- Descarga (bytes/s -> Mbps) ---
DL_BPS=$(curl -s -o /dev/null --max-time "$MAX_TIME" -w '%{speed_download}' "$DL_URL" 2>/dev/null)
DL_MBPS=$(awk -v b="${DL_BPS:-0}" 'BEGIN{printf "%.1f", b*8/1000000}')

# --- Subida (bytes/s -> Mbps) ---
UL_BPS=$(dd if=/dev/zero bs=1048576 count="$UL_MB" 2>/dev/null | \
    curl -s -o /dev/null --max-time "$MAX_TIME" -w '%{speed_upload}' \
    -H 'Content-Type: application/octet-stream' --data-binary @- "$UL_URL" 2>/dev/null)
UL_MBPS=$(awk -v b="${UL_BPS:-0}" 'BEGIN{printf "%.1f", b*8/1000000}')

# --- Registro CSV ---
[ -f "$LOG_FILE" ] || echo "fecha,latencia_ms,latencia_max_ms,descarga_mbps,subida_mbps" > "$LOG_FILE"
echo "$TS,$LAT_AVG,$LAT_MAX,$DL_MBPS,$UL_MBPS" >> "$LOG_FILE"

# --- Rotacion ---
LINES=$(wc -l < "$LOG_FILE")
if [ "$LINES" -gt "$MAX_LINES" ]; then
    { head -1 "$LOG_FILE"; tail -n "$MAX_LINES" "$LOG_FILE"; } > "${LOG_FILE}.tmp" \
        && mv "${LOG_FILE}.tmp" "$LOG_FILE"
fi

echo "$TS | ping ${LAT_AVG}ms | down ${DL_MBPS} Mbps | up ${UL_MBPS} Mbps"
