#!/usr/bin/env python3
"""Filter a candump -L capture down to a subset of CAN IDs.

Usage:
    python3 filterlog.py left.log 188,244,19B,1F2 > subset_A.log

The second argument is a comma-separated list of CAN IDs (hex, case
insensitive). Matching lines are written to stdout verbatim, so the
output stays a valid candump -L log that canplayer can replay with
original timing preserved:

    canplayer -I subset_A.log -l i vcan0=vcan0
"""

import re
import sys

LINE_RE = re.compile(
    r"^\((\d+(?:\.\d+)?)\)\s+(\S+)\s+([0-9A-Fa-f]+)#(\S*)\s*$"
)


def main():
    if len(sys.argv) != 3:
        sys.exit(
            "usage: python3 filterlog.py <capture.log> <id1,id2,...>"
        )

    path = sys.argv[1]
    wanted = set()
    for tok in sys.argv[2].split(","):
        tok = tok.strip()
        if not tok:
            continue
        try:
            wanted.add("{:X}".format(int(tok, 16)))
        except ValueError:
            sys.exit("not a valid hex CAN ID: {!r}".format(tok))

    if not wanted:
        sys.exit("no valid IDs given")

    kept = 0
    total = 0
    with open(path, "r", errors="replace") as fh:
        for line in fh:
            stripped = line.rstrip("\n")
            m = LINE_RE.match(stripped)
            if not m:
                continue  # skip non-frame lines
            total += 1
            cid = m.group(3).upper()
            if cid in wanted:
                sys.stdout.write(line if line.endswith("\n") else stripped + "\n")
                kept += 1

    sys.stderr.write(
        "kept {}/{} frames, IDs: {}\n".format(
            kept, total, ",".join(sorted(wanted, key=lambda x: int(x, 16)))
        )
    )


if __name__ == "__main__":
    main()
