#!/bin/sh
# busrouter-status: CGI endpoint that reads state files and returns JSON.
STATE=/tmp/busrouter

printf 'Content-Type: application/json\r\n\r\n'

_read_file() { cat "$1" 2>/dev/null | head -n 1 || echo "${2:-}"; }

_cgi_str() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; }

_metric_json() {
    local file="$1" has_rsrp="$2"
    [ -f "$file" ] || { echo 'null'; return; }
    read -r lat dl ul jitter loss rsrp < "$file" 2>/dev/null
    if [ "$has_rsrp" = "1" ] && [ -n "$rsrp" ]; then
        printf '{"latency_ms":%s,"dl_mbps":%s,"ul_mbps":%s,"jitter_ms":%s,"loss_pct":%s,"rsrp_dbm":%s}' \
            "${lat:-0}" "${dl:-0}" "${ul:-0}" "${jitter:-0}" "${loss:-100}" "${rsrp:-null}"
    else
        printf '{"latency_ms":%s,"dl_mbps":%s,"ul_mbps":%s,"jitter_ms":%s,"loss_pct":%s}' \
            "${lat:-0}" "${dl:-0}" "${ul:-0}" "${jitter:-0}" "${loss:-100}"
    fi
}

now=$(date +%s)
ver=$(_read_file /etc/busrouter/version "dev")
uptime_s=$(awk '{printf "%d", $1}' /proc/uptime 2>/dev/null || echo 0)
device_id=$(cat /etc/busrouter/device-id 2>/dev/null || hostname)

cell_score=$(_read_file "${STATE}/score_modem_0001" 0)
wan_score=$(_read_file "${STATE}/score_wan" 0)
cell_weight=$(uci -q get mwan3.modem_0001.weight 2>/dev/null || echo null)
wan_weight=$(uci -q get mwan3.wan.weight 2>/dev/null || echo null)
sim_slot=$(_read_file "${STATE}/sim_slot" null)

gps_lat="" gps_lon="" gps_fix=""
[ -f "${STATE}/gps_last" ] && read -r gps_lat gps_lon gps_fix < "${STATE}/gps_last" 2>/dev/null

sl_lat="" sl_dl="" sl_obs="" sl_outage=""
[ -f "${STATE}/starlink_last" ] && read -r sl_lat sl_dl sl_obs sl_outage < "${STATE}/starlink_last" 2>/dev/null

buf_count=$(find "${STATE}/telemetry-buf" -name '*.json' 2>/dev/null | wc -l)

cell_metrics=$(_metric_json "${STATE}/metric_modem_0001" 1)
wan_metrics=$(_metric_json "${STATE}/metric_wan" 0)

esc_ver=$(_cgi_str "$ver")
esc_id=$(_cgi_str "$device_id")

printf '{
  "timestamp":%d,
  "uptime":%d,
  "version":"%s",
  "device_id":"%s",
  "cellular":{
    "score":%s,
    "weight":%s,
    "metrics":%s
  },
  "wan":{
    "score":%s,
    "weight":%s,
    "metrics":%s
  },
  "sim_slot":%s,
  "gps":{"lat":%s,"lon":%s,"fix":%s},
  "starlink":{"latency_ms":%s,"dl_mbps":%s,"obstructed":%s,"outage":%s},
  "telemetry_buffered":%d
}\n' \
    "${now}" "${uptime_s}" "${esc_ver}" "${esc_id}" \
    "${cell_score:-0}" "${cell_weight:-null}" "${cell_metrics}" \
    "${wan_score:-0}" "${wan_weight:-null}" "${wan_metrics}" \
    "${sim_slot:-null}" \
    "${gps_lat:-null}" "${gps_lon:-null}" "${gps_fix:-null}" \
    "${sl_lat:-null}" "${sl_dl:-null}" "${sl_obs:-0}" "${sl_outage:-0}" \
    "${buf_count:-0}"
