#!/usr/bin/env python3
"""arpwatch - ARP table entries with MAC, IP, and interface.
Usage: arpwatch [-w SECONDS] [--selftest]
  Reads /proc/net/arp into a table (IP, hardware type, flags, MAC,
  interface) and flags incomplete entries. With -w it polls and reports
  NEW, CHANGED (MAC moved — possible spoofing), and GONE entries with
  timestamps. The twist vs `arp -a`: the watch mode turns a static table
  into a LAN change log.
"""
import argparse
import sys
import time

SAMPLE = """IP address       HW type     Flags       HW address            Mask     Device
192.168.1.1      0x1         0x2         aa:bb:cc:dd:ee:ff     *        enp3s0
192.168.1.42     0x1         0x2         11:22:33:44:55:66     *        enp3s0
192.168.1.99     0x1         0x0         00:00:00:00:00:00     *        enp3s0
"""


def parse_arp(text):
    entries = {}
    for line in text.splitlines():
        parts = line.split()
        if len(parts) < 6 or parts[0] == "IP":
            continue
        try:
            flags = int(parts[2], 16)
        except ValueError:
            flags = 0
        entries[parts[0]] = {"hwtype": parts[1], "flags": flags,
                             "mac": parts[3], "iface": parts[5],
                             "complete": bool(flags & 0x2)}
    return entries


def read_arp():
    try:
        with open("/proc/net/arp") as f:
            return parse_arp(f.read())
    except OSError as e:
        print(f"arpwatch: cannot read /proc/net/arp: {e}", file=sys.stderr)
        return {}


def report(entries):
    print(f"{'IP':<16} {'MAC':<18} {'IFACE':<10} {'STATE':<10}")
    for ip in sorted(entries, key=lambda i: tuple(int(x) for x in i.split(".")) if i.count(".") == 3 else i):
        e = entries[ip]
        state = "complete" if e["complete"] else "INCOMPLETE"
        print(f"{ip:<16} {e['mac']:<18} {e['iface']:<10} {state:<10}")
    incomplete = sum(1 for e in entries.values() if not e["complete"])
    if incomplete:
        print(f"note: {incomplete} incomplete entr{'y' if incomplete == 1 else 'ies'} (unanswered ARP).")
    print(f"{len(entries)} ARP entr{'y' if len(entries) == 1 else 'ies'}.")


def watch_loop(seconds):
    prev = read_arp()
    print(f"baseline: {len(prev)} entries; watching for {seconds:g}s ...")
    start = time.time()
    while time.time() - start < seconds:
        time.sleep(2)
        cur = read_arp()
        stamp = time.strftime("%H:%M:%S")
        for ip, e in cur.items():
            if ip not in prev:
                print(f"[{stamp}] NEW     {ip} {e['mac']} on {e['iface']}")
            elif prev[ip]["mac"] != e["mac"]:
                print(f"[{stamp}] CHANGED {ip} {prev[ip]['mac']} -> {e['mac']} (MAC moved — check for spoofing)")
        for ip in prev:
            if ip not in cur:
                print(f"[{stamp}] GONE    {ip} was {prev[ip]['mac']}")
        prev = cur
    print("watch done.")


def selftest():
    entries = parse_arp(SAMPLE)
    assert len(entries) == 3, entries
    assert entries["192.168.1.1"]["mac"] == "aa:bb:cc:dd:ee:ff"
    assert entries["192.168.1.1"]["complete"] is True
    assert entries["192.168.1.99"]["complete"] is False
    print("selftest: parsed sample ARP table:")
    report(entries)
    live = read_arp()
    print(f"selftest: live /proc/net/arp has {len(live)} entr{'y' if len(live) == 1 else 'ies'} — OK")
    return 0


def main():
    ap = argparse.ArgumentParser(description="arpwatch - ARP table entries with MAC, IP, and interface")
    ap.add_argument("-w", "--watch", type=float, default=0, help="watch for N seconds, reporting NEW/CHANGED/GONE")
    ap.add_argument("--selftest", action="store_true", help="parse an embedded sample ARP table + read the live one")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    if args.watch > 0:
        try:
            watch_loop(args.watch)
        except KeyboardInterrupt:
            print("stopped.")
        return 0
    report(read_arp())
    return 0


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