#!/usr/bin/env bash
set -euo pipefail

TARGET="${1:-100.90.121.70}"
OUT="${2:-docker/skippy-wan-lab/.env.link}"
PING_COUNT="${PING_COUNT:-10}"
IPERF_SECONDS="${IPERF_SECONDS:-5}"

if ! command -v ping >/dev/null 2>&1; then
  echo "ping is required" >&2
  exit 1
fi

ping_output="$(ping -c "$PING_COUNT" "$TARGET")"
avg_rtt="$(
  printf '%s\n' "$ping_output" \
    | awk -F'=' '/min\/avg\/max|round-trip/ {gsub(/^[ \t]+/, "", $2); split($2, a, "/"); print a[2]}'
)"

if [[ -z "$avg_rtt" ]]; then
  echo "could not parse average RTT from ping output:" >&2
  printf '%s\n' "$ping_output" >&2
  exit 1
fi

one_way="$(python3 - "$avg_rtt" <<'PY'
import sys
print(f"{float(sys.argv[1]) / 2.0:.3f}")
PY
)"

rate_mbit=""
if command -v iperf3 >/dev/null 2>&1; then
  if iperf_json="$(iperf3 -c "$TARGET" -J -t "$IPERF_SECONDS" 2>/dev/null)"; then
    rate_mbit="$(
      IPERF_JSON="$iperf_json" python3 - <<'PY'
import json
import os
import sys
data = json.loads(os.environ["IPERF_JSON"])
sender = data.get("end", {}).get("sum_sent") or data.get("end", {}).get("sum")
if sender and sender.get("bits_per_second"):
    print(max(1, round(sender["bits_per_second"] / 1_000_000)))
PY
    )"
  fi
fi

mkdir -p "$(dirname "$OUT")"
cat >"$OUT" <<EOF
# Generated by scripts/skippy-wan-calibrate.sh for ${TARGET}
# Average ping RTT: ${avg_rtt} ms
WAN_RTT_MS=${avg_rtt}
WAN_DELAY_MS=${one_way}
WAN_JITTER_MS=0
WAN_LOSS_PERCENT=0
EOF

if [[ -n "$rate_mbit" ]]; then
  printf 'WAN_RATE_MBIT=%s\n' "$rate_mbit" >>"$OUT"
else
  cat >>"$OUT" <<'EOF'
# iperf3 did not produce a target bandwidth measurement.
# Fill this in manually if you want bandwidth shaping as well as latency.
WAN_RATE_MBIT=
EOF
fi

cat <<EOF
wrote ${OUT}
target=${TARGET}
avg_rtt_ms=${avg_rtt}
one_way_delay_ms=${one_way}
wan_rate_mbit=${rate_mbit:-unset}
EOF
