#!/usr/bin/env python3
"""mountlist - all mounts with type, size, free space, and ro/rw flag.
Usage: mountlist [--type TYPE] [--sort size|free|used|name] [--selftest]"""
import argparse, os, sys

def human(n):
    for u in ("B", "K", "M", "G", "T"):
        if abs(n) < 1024 or u == "T":
            return f"{n:.1f}{u}" if u != "B" else f"{int(n)}B"
        n /= 1024.0
    return f"{n:.1f}T"

def get_mounts():
    out = []
    with open("/proc/mounts") as f:
        for line in f:
            p = line.split()
            if len(p) < 4:
                continue
            dev, mp, fs, opts = p[0], p[1], p[2], p[3].split(",")
            total = free = None
            try:
                st = os.statvfs(mp)
                total = st.f_blocks * st.f_frsize
                free = st.f_bavail * st.f_frsize
            except OSError:
                pass
            out.append({"dev": dev, "mp": mp, "fs": fs,
                        "ro": "ro" in opts, "total": total, "free": free,
                        "pct": (100.0 * (total - free) / total) if total else None})
    return out

def selftest():
    rows = get_mounts()
    ok = True
    if not rows:
        print("FAIL: no mounts"); ok = False
    if not any(r["mp"] == "/" for r in rows):
        print("FAIL: root mount missing"); ok = False
    for r in rows:
        if r["total"] is not None and not (0 <= (r["pct"] or 0) <= 100):
            print(f"FAIL: bad pct for {r['mp']}"); ok = False
    if ok:
        print(f"selftest: PASS ({len(rows)} mounts, root present)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="mountlist",
        description="All mounts with type, size, free space, and ro/rw flag.")
    ap.add_argument("--type", help="only show this filesystem type")
    ap.add_argument("--sort", default="name", choices=["size", "free", "used", "name"],
                    help="sort key (default: name)")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks on live mounts")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    rows = get_mounts()
    if a.type:
        rows = [r for r in rows if r["fs"] == a.type]
    key = {"name": lambda r: r["mp"], "size": lambda r: -(r["total"] or 0),
           "free": lambda r: -(r["free"] or 0), "used": lambda r: -(r["pct"] or 0)}[a.sort]
    rows.sort(key=key)
    print(f"{'MOUNT':<28} {'DEVICE':<22} {'FS':<10} {'SIZE':>9} {'FREE':>9} {'USED%':>6}  MODE")
    for r in rows:
        total = human(r["total"]) if r["total"] is not None else "-"
        free = human(r["free"]) if r["free"] is not None else "-"
        pct = f"{r['pct']:.1f}%" if r["pct"] is not None else "-"
        print(f"{r['mp']:<28} {r['dev']:<22} {r['fs']:<10} {total:>9} {free:>9} {pct:>6}  {'ro' if r['ro'] else 'rw'}")
    return 0

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