#!/usr/bin/env python3
"""nettrace - trace the route to a host with per-hop latency (ping TTL method).
Usage: nettrace HOST [-m MAXHOPS] [--selftest]
  Sends one ping per hop with increasing TTL (-t) and records the first
  responder at each TTL, with its round-trip time — the classic traceroute
  idea using only the system ping, so it needs no raw sockets. Stops early
  when the target itself answers. Hops that stay silent are shown as `*`.
"""
import argparse
import re
import shutil
import subprocess
import sys

FROM_RE = re.compile(r"from\s+(\S+)")
TIME_RE = re.compile(r"time[=<]([\d.]+)\s*ms")


def probe_hop(host, ttl, timeout=2):
    ping = shutil.which("ping")
    if not ping:
        raise RuntimeError("ping command not found")
    proc = subprocess.run(
        [ping, "-c", "1", "-t", str(ttl), "-W", str(timeout), host],
        capture_output=True, text=True, timeout=timeout + 5)
    out = proc.stdout + proc.stderr
    m = FROM_RE.search(out)
    t = TIME_RE.search(out)
    if m:
        return m.group(1).strip("(): "), float(t.group(1)) if t else None
    return None, None


def trace(host, max_hops=30):
    hops = []
    for ttl in range(1, max_hops + 1):
        addr, ms = probe_hop(host, ttl)
        hops.append((ttl, addr, ms))
        if addr is None:
            continue
        # reached the target when the responder resolves to the target name/ip
        try:
            target_ip = __import__("socket").gethostbyname(host)
        except OSError:
            target_ip = None
        if addr == host or addr == target_ip:
            break
    return hops


def selftest():
    print("selftest: tracing 127.0.0.1 (should be 1 hop)")
    hops = trace("127.0.0.1", max_hops=3)
    for ttl, addr, ms in hops:
        print(f"  {ttl}  {addr or '*'}  {f'{ms:.1f} ms' if ms is not None else ''}")
    ok = len(hops) >= 1 and hops[0][1] in ("127.0.0.1", "localhost")
    print(f"selftest: {'OK' if ok else 'FAIL'} — first hop is {hops[0][1] if hops else 'missing'}")
    return 0 if ok else 1


def main():
    ap = argparse.ArgumentParser(description="nettrace - trace the route to a host with per-hop latency")
    ap.add_argument("host", nargs="?", help="host to trace to")
    ap.add_argument("-m", "--max-hops", type=int, default=30, help="maximum hops (default 30)")
    ap.add_argument("--selftest", action="store_true", help="trace 127.0.0.1 (1 hop)")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    if not args.host:
        ap.error("HOST is required (or use --selftest)")
    try:
        hops = trace(args.host, args.max_hops)
    except RuntimeError as e:
        print(f"nettrace: {e}", file=sys.stderr)
        return 1
    print(f"trace to {args.host}:")
    for ttl, addr, ms in hops:
        if addr is None:
            print(f" {ttl:2d}  *")
        else:
            print(f" {ttl:2d}  {addr:<24} {f'{ms:.1f} ms' if ms is not None else ''}")
    return 0


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