#!/usr/bin/env bash
# Replay-based bisection: split the candidate ID set into two halves and
# write a replayable log for each (original timing preserved).
# Needs filterlog.py in the same directory.
#
# usage: ./bisect.sh <capture.log> <id1,id2,...>
#
# Then replay each half and watch the cluster:
#   canplayer -I subset_A.log -l i vcan0=vcan0
#   canplayer -I subset_B.log -l i vcan0=vcan0
set -euo pipefail
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
log=${1:?usage: ./bisect.sh <capture.log> <id1,id2,...>}
ids=${2:?usage: ./bisect.sh <capture.log> <id1,id2,...>}

n=$(echo "$ids" | tr ',' '\n' | grep -c .)
half=$(( (n + 1) / 2 ))
A=$(echo "$ids" | tr ',' '\n' | head -n "$half" | paste -sd,)
B=$(echo "$ids" | tr ',' '\n' | tail -n +$((half + 1)) | paste -sd,)

python3 "$SCRIPT_DIR/filterlog.py" "$log" "$A" > subset_A.log
echo "A = $A -> subset_A.log"
if [ -n "$B" ]; then
    python3 "$SCRIPT_DIR/filterlog.py" "$log" "$B" > subset_B.log
    echo "B = $B -> subset_B.log"
fi
echo
echo "replay A:  canplayer -I subset_A.log -l i vcan0=vcan0"
[ -n "$B" ] && echo "replay B:  canplayer -I subset_B.log -l i vcan0=vcan0"
echo "effect on A -> keep A as new S; effect on B -> keep B; none or both -> recheck the candidate set"
