#!/usr/bin/env bash
# Capture paired sender/receiver logcat for alpha QA (run from repo root).
set -euo pipefail

SENDER="${1:-}"
RECEIVER="${2:-}"
STAMP="$(date +%Y%m%d-%H%M%S)"
OUT_DIR="$(dirname "$0")/../alpha-logs-${STAMP}"
mkdir -p "$OUT_DIR"

TAGS='ScreenCastService:* ReceiverCastService:* AndroidCast:* SenderScreenPreview:* CastProtocol:*'

adb_cmd() {
  local serial="$1"
  shift
  if [[ -n "$serial" ]]; then
    adb -s "$serial" "$@"
  else
    adb "$@"
  fi
}

echo "Writing logs to $OUT_DIR"
echo "Press Ctrl+C to stop."

if [[ -n "$SENDER" ]]; then
  adb_cmd "$SENDER" logcat -c
fi
if [[ -n "$RECEIVER" && "$RECEIVER" != "$SENDER" ]]; then
  adb_cmd "$RECEIVER" logcat -c
fi

trap 'echo; echo "Stopped."' INT

if [[ -n "$SENDER" ]]; then
  adb_cmd "$SENDER" logcat $TAGS | tee "$OUT_DIR/sender.log" &
  PID_S=$!
fi
if [[ -n "$RECEIVER" && "$RECEIVER" != "$SENDER" ]]; then
  adb_cmd "$RECEIVER" logcat $TAGS | tee "$OUT_DIR/receiver.log" &
  PID_R=$!
elif [[ -z "$SENDER" ]]; then
  adb logcat $TAGS | tee "$OUT_DIR/combined.log"
  exit 0
fi

wait ${PID_S:-} ${PID_R:-}
