#!/usr/bin/env python3
"""ipinfo - all interfaces, IPs, MTU, and gateway in one table.
Usage: ipinfo [--selftest]
  One table: interface, state, MAC, IPv4/IPv6 addresses, MTU, and the
  default gateway (from /proc/net/route). Sources are /sys/class/net and
  socket.if_nameindex so it works without the `ip` command; `ip addr` /
  `ip route` output is used only as a fallback for addresses.
"""
import argparse
import os
import re
import socket
import subprocess
import sys


def read_sys(iface, name):
    try:
        with open(f"/sys/class/net/{iface}/{name}") as f:
            return f.read().strip()
    except OSError:
        return None


def gateway():
    try:
        with open("/proc/net/route") as f:
            next(f)
            for line in f:
                parts = line.split()
                if len(parts) >= 3 and parts[1] == "00000000":
                    gw_hex = parts[2]
                    b = bytes.fromhex(gw_hex)
                    return ".".join(str(x) for x in reversed(b)), parts[0]
    except OSError:
        pass
    return None, None


def addrs_from_ip():
    """Fallback: parse `ip -o addr` if present. Returns {iface: [addrs]}."""
    out = {}
    try:
        r = subprocess.run(["ip", "-o", "addr"], capture_output=True, text=True, timeout=5)
    except (OSError, subprocess.SubprocessError):
        return out
    for line in r.stdout.splitlines():
        m = re.match(r"\d+:\s+(\S+)\s+inet6?\s+(\S+)", line)
        if m:
            out.setdefault(m.group(1), []).append(m.group(2))
    return out


def collect():
    rows = []
    gw_ip, gw_iface = gateway()
    ip_addrs = addrs_from_ip()
    for _, iface in socket.if_nameindex():
        addrs = []
        # socket-based IPv4 for this iface is not directly available; use ip fallback
        addrs = ip_addrs.get(iface, [])
        if not addrs:
            # last resort: hostname resolution only tells us one address; only
            # use it for loopback, where it is unambiguous
            if iface == "lo":
                addrs = ["127.0.0.1/8", "::1/128"]
        rows.append({
            "iface": iface,
            "state": read_sys(iface, "operstate") or "?",
            "mac": read_sys(iface, "address") or "?",
            "mtu": read_sys(iface, "mtu") or "?",
            "addrs": addrs,
            "gw": gw_ip if iface == gw_iface else "",
        })
    return rows, gw_ip, gw_iface


def report(rows, gw_ip, gw_iface):
    print(f"{'INTERFACE':<12} {'STATE':<8} {'MAC':<18} {'MTU':>5}  ADDRESSES")
    for r in rows:
        addrs = ", ".join(r["addrs"]) if r["addrs"] else "(none)"
        print(f"{r['iface']:<12} {r['state']:<8} {r['mac']:<18} {r['mtu']:>5}  {addrs}")
    if gw_ip:
        print(f"\nDefault gateway: {gw_ip} via {gw_iface}")
    else:
        print("\nDefault gateway: (none found in /proc/net/route)")


def selftest():
    rows, gw_ip, gw_iface = collect()
    names = [r["iface"] for r in rows]
    assert "lo" in names, "loopback interface missing"
    lo = next(r for r in rows if r["iface"] == "lo")
    assert "127.0.0.1/8" in lo["addrs"], f"lo addresses wrong: {lo['addrs']}"
    print("selftest: interfaces found:", ", ".join(names))
    report(rows, gw_ip, gw_iface)
    print("selftest: lo present with 127.0.0.1 — OK")
    return 0


def main():
    ap = argparse.ArgumentParser(description="ipinfo - all interfaces, IPs, MTU, and gateway in one table")
    ap.add_argument("--selftest", action="store_true", help="collect the live table and check lo is present")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    rows, gw_ip, gw_iface = collect()
    report(rows, gw_ip, gw_iface)
    return 0


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