#!/usr/bin/env python3
"""hardlink - find files with multiple hard links and report the link groups.
Usage: hardlink [dir] [--min-links N] [--selftest] [--help]
Groups files by (device, inode) and reports every inode with more than one
link in the tree, listing all its paths, the link count, and the bytes that
would be freed by keeping only one copy (i.e. the shared-data saving if you
deduplicated). This is the `find -links +1` answer with the actual groups
and the space math included.
"""
import argparse, os, sys, tempfile
from pathlib import Path
from collections import defaultdict

def human(n):
    for u in ("B", "KiB", "MiB", "GiB", "TiB"):
        if abs(n) < 1024 or u == "TiB":
            return f"{n:.1f} {u}" if u != "B" else f"{n} B"
        n /= 1024

def find_groups(root, min_links=2):
    groups = defaultdict(list)
    for p in root.rglob("*"):
        if p.is_file() and not p.is_symlink():
            try:
                st = p.stat()
            except OSError:
                continue
            if st.st_nlink >= min_links:
                groups[(st.st_dev, st.st_ino)].append((p, st))
    return {k: v for k, v in groups.items() if len(v) >= min_links}

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        orig = base / "orig.bin"
        orig.write_bytes(b"Z" * 1000)
        os.link(orig, base / "alias.bin")
        (base / "single.bin").write_bytes(b"Q" * 100)
        groups = find_groups(base)
        assert len(groups) == 1, groups
        members = next(iter(groups.values()))
        assert len(members) == 2 and members[0][1].st_nlink == 2, members
        assert members[0][1].st_size == 1000
        print("selftest OK: 1 hard-link group (2 paths, nlink 2), single-link file excluded")
        return 0

def main():
    ap = argparse.ArgumentParser(description="hardlink - find files with multiple hard links, grouped")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--min-links", type=int, default=2)
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    root = Path(a.dir)
    if not root.is_dir():
        print(f"hardlink: {a.dir}: not a directory", file=sys.stderr); return 2
    groups = find_groups(root, a.min_links)
    if not groups:
        print(f"no files with {a.min_links}+ hard links under {root}"); return 0
    total_saved = 0
    for (dev, ino), members in sorted(groups.items(), key=lambda kv: -kv[1][0][1].st_size):
        size = members[0][1].st_size
        nlink = members[0][1].st_nlink
        total_saved += size * (len(members) - 1)
        print(f"inode {ino} on dev {dev}: {nlink} link(s), {human(size)} each")
        for p, _ in members:
            print(f"  {p}")
    print(f"\n{len(groups)} hard-link group(s); keeping one copy per group would free "
          f"{human(total_saved)} (shared data counted once)")
    return 0

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