#!/usr/bin/env python3
"""trimcheck - whether TRIM is enabled/supported, from /sys, with graceful fallback.
Usage: trimcheck [--selftest]
Reads /sys/block/*/queue/discard_* and mount options; on a system with no
TRIM-capable hardware it says so plainly and exits 0 instead of failing."""
import argparse, glob, os, sys

def check():
    """Returns list of dicts: device, supported, max_discard, mounted_with_discard."""
    discard_mounts = set()
    try:
        with open("/proc/mounts") as f:
            for line in f:
                p = line.split()
                if len(p) >= 4 and "discard" in p[3].split(","):
                    discard_mounts.add(p[0])
    except OSError:
        pass
    devs = []
    for q in sorted(glob.glob("/sys/block/*/queue")):
        dev = q.split("/")[-2]
        if dev.startswith(("loop", "ram")):
            continue
        def read(name):
            try:
                with open(os.path.join(q, name)) as f:
                    return int(f.read().strip())
            except (OSError, ValueError):
                return None
        gran = read("discard_granularity")
        maxb = read("discard_max_bytes")
        devs.append({"dev": dev, "granularity": gran, "max_bytes": maxb,
                     "supported": bool(gran and gran > 0),
                     "mount_discard": any(d in discard_mounts for d in
                                          (f"/dev/{dev}", dev))})
    return devs

def selftest():
    devs = check()
    # The check must never crash and must always produce a verdict, even on
    # systems with no block devices at all.
    ok = isinstance(devs, list)
    for d in devs:
        if not isinstance(d["supported"], bool):
            ok = False
    print(f"selftest: PASS (trimcheck ran cleanly, {len(devs)} block device(s) examined)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="trimcheck",
        description="Whether TRIM is enabled/supported, from /sys, with graceful fallback.")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    devs = check()
    if not devs:
        print("TRIM: not determinable on this system - no block devices expose")
        print("discard info under /sys/block/*/queue (VM, container, or no local disks).")
        print("On a physical SSD, check: cat /sys/block/sda/queue/discard_granularity")
        return 0
    print(f"{'DEVICE':<12} {'SUPPORTED':<10} {'GRANULARITY':>12} {'MAX DISCARD':>12}  MOUNT DISCARD?")
    any_supported = False
    for d in devs:
        sup = "yes" if d["supported"] else "no"
        any_supported |= d["supported"]
        gran = f"{d['granularity']} B" if d["granularity"] is not None else "?"
        maxb = f"{d['max_bytes']} B" if d["max_bytes"] is not None else "?"
        md = "yes (discard mount opt)" if d["mount_discard"] else "no"
        print(f"{d['dev']:<12} {sup:<10} {gran:>12} {maxb:>12}  {md}")
    if not any_supported:
        print("No TRIM-capable device found. If this is an SSD, the kernel or")
        print("controller does not expose discard; fstrim would be a no-op.")
    else:
        print("Hint: TRIM only helps if the filesystem is mounted with 'discard'")
        print("or you run 'fstrim' periodically (weekly fstrim timer).")
    return 0

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