#!/usr/bin/env python3
"""multicast - list multicast group memberships.
Usage: multicast [--selftest]
  Reads /proc/net/igmp (IPv4) and /proc/net/igmp6 (IPv6): which interfaces
  have joined which multicast groups, with group counts. The twist vs
  `ip maddr`: it also decodes the well-known groups (224.0.0.1 all-hosts,
  224.0.0.251 mDNS, 239.255.255.250 SSDP...) so the table says what the
  group is for, not just a hex address.
"""
import argparse
import sys

KNOWN = {
    "224.0.0.1": "all-hosts",
    "224.0.0.2": "all-routers",
    "224.0.0.5": "OSPF all-routers",
    "224.0.0.6": "OSPF designated-routers",
    "224.0.0.9": "RIPv2",
    "224.0.0.13": "PIM routers",
    "224.0.0.22": "IGMPv3",
    "224.0.0.251": "mDNS (Bonjour/Avahi)",
    "224.0.1.1": "NTP",
    "239.255.255.250": "SSDP/UPnP",
    "239.255.255.253": "SLP",
    "224.0.0.252": "LLMNR",
}


def parse_igmp(text):
    """Return {iface: {group_ip: users}} from /proc/net/igmp text.
    Real format: device lines are `N  iface : count V3`; group lines are
    an 8-hex-digit little-endian address plus a user count. (010000E0 is
    224.0.0.1: the bytes reverse, as in /proc/net/tcp.)"""
    groups = {}
    iface = None
    hexdigits = set("0123456789ABCDEFabcdef")
    for line in text.splitlines():
        parts = line.split()
        if not parts:
            continue
        if parts[0].isdigit() and len(parts) >= 2 and ":" in parts:
            iface = parts[1]
            groups.setdefault(iface, {})
            continue
        if iface and len(parts) >= 2 and len(parts[0]) == 8 and set(parts[0]) <= hexdigits:
            try:
                users = int(parts[1])
                b = bytes.fromhex(parts[0])
                ip = ".".join(str(x) for x in reversed(b))
            except ValueError:
                continue
            if users > 0:
                groups[iface][ip] = users
    return groups


def parse_igmp6(text):
    """Return {iface: [group]} from /proc/net/igmp6 text.
    Real format per line: index, device name, 32-hex-digit group, users, ..."""
    groups = {}
    for line in text.splitlines():
        parts = line.split()
        if len(parts) >= 4 and parts[0].isdigit():
            iface = parts[1]
            group = parts[2]
            try:
                users = int(parts[3])
            except ValueError:
                try:
                    users = int(parts[3], 16)
                except ValueError:
                    continue
            if users > 0:
                groups.setdefault(iface, []).append(group)
    return groups


def collect():
    v4, v6 = {}, {}
    try:
        with open("/proc/net/igmp") as f:
            v4 = parse_igmp(f.read())
    except OSError:
        pass
    try:
        with open("/proc/net/igmp6") as f:
            v6 = parse_igmp6(f.read())
    except OSError:
        pass
    return v4, v6


def selftest():
    sample = """Idx\tDevice    : Count Querier\tGroup    Users Timer\tReporter
1\tlo        :     0      V3
\t\t\t\t010000E0     1 0:00000000\t\t0
2\tenp3s0    :     1      V3
\t\t\t\tFB0000E0     1 0:00000000\t\t0
\t\t\t\tFAFFFFEF     1 0:00000000\t\t0
"""
    v4 = parse_igmp(sample)
    assert "lo" in v4 and "224.0.0.1" in v4["lo"], f"sample parse failed: {v4}"
    assert "224.0.0.251" in v4["enp3s0"], f"mDNS group missing: {v4}"
    assert "239.255.255.250" in v4["enp3s0"], f"SSDP group missing: {v4}"
    print("selftest: sample /proc/net/igmp parsed:")
    for iface, groups in v4.items():
        for ip, users in groups.items():
            print(f"  {iface:<10} {ip:<16} users={users}  {KNOWN.get(ip, '')}")
    print("selftest: known groups decoded (all-hosts, mDNS, SSDP) — OK")
    return 0


def main():
    ap = argparse.ArgumentParser(description="multicast - list multicast group memberships")
    ap.add_argument("--selftest", action="store_true", help="parse an embedded sample /proc/net/igmp")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    v4, v6 = collect()
    if not v4 and not v6:
        print("multicast: no multicast group memberships found (or /proc/net/igmp unreadable).")
        return 0
    print(f"{'INTERFACE':<12} {'GROUP':<18} {'USERS':>5}  WHAT")
    for iface in sorted(v4):
        for ip in sorted(v4[iface]):
            print(f"{iface:<12} {ip:<18} {v4[iface][ip]:>5}  {KNOWN.get(ip, '')}")
    for iface in sorted(v6):
        for group in v6[iface]:
            print(f"{iface:<12} {group:<18} {'-':>5}  (IPv6)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
