#!/usr/bin/env bash
# Capture VP9+FEC cast logs from sender (.106) and receiver (.39).
# Usage: ./scripts/capture-vp9-fec-logs.sh [label]
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CAP="$ROOT/.log_capture"
TS="$(date +%Y%m%d_%H%M%S)"
LABEL="${1:-fec}"
mkdir -p "$CAP"

SENDER="192.168.33.106:5555"
RECEIVER="192.168.33.39:5555"

adb connect "$SENDER" >/dev/null 2>&1 || true
adb connect "$RECEIVER" >/dev/null 2>&1 || true

FILTER='FEC|Fec|fec|UdpCast|StreamProtection|Protection|reasm|ReedSolomon|shard|ScreenCast|Libvpx|ReceiverCast|ReceiverSession|VideoDecoder|NativeCodec|CodecPriority|CastFanout|CastSendPump|NetworkFeedback|transportLoss|decode|keyframe|awaiting|AudioDecoder|drop'

echo "==> Clearing logcat buffers"
adb -s "$SENDER" logcat -c 2>/dev/null || true
adb -s "$RECEIVER" logcat -c 2>/dev/null || true

SPID=$(adb -s "$SENDER" shell pidof com.foxx.androidcast 2>/dev/null | tr -d '\r' || true)
RPID=$(adb -s "$RECEIVER" shell pidof com.foxx.androidcast 2>/dev/null | tr -d '\r' || true)
echo "==> PIDs sender=$SPID receiver=$RPID"

echo "==> Recording 90s (start cast now)..."
timeout 90 adb -s "$SENDER" logcat -v threadtime 2>&1 | grep -iE "$FILTER" > "$CAP/${LABEL}_sender_106_${TS}.log" &
PID_S=$!
timeout 90 adb -s "$RECEIVER" logcat -v threadtime 2>&1 | grep -iE "$FILTER" > "$CAP/${LABEL}_receiver_39_${TS}.log" &
PID_R=$!
wait "$PID_S" "$PID_R" 2>/dev/null || true

# Snapshot dumps after live capture
adb -s "$SENDER" logcat -d --pid="$SPID" -t 8000 > "$CAP/${LABEL}_sender_pid_${TS}.log" 2>&1 || true
adb -s "$RECEIVER" logcat -d --pid="$RPID" -t 8000 > "$CAP/${LABEL}_receiver_pid_${TS}.log" 2>&1 || true
adb -s "$SENDER" logcat -d -b crash -t 50 2>&1 > "$CAP/${LABEL}_sender_crash_${TS}.log" || true
adb -s "$RECEIVER" logcat -d -b crash -t 50 2>&1 > "$CAP/${LABEL}_receiver_crash_${TS}.log" || true

echo "==> Saved under $CAP/${LABEL}_*_${TS}.log"
wc -c "$CAP"/${LABEL}_*_${TS}.log 2>/dev/null | tail -6
