#!/usr/bin/env python3
"""fscheck - filesystem type, mount options, and free space per mount in one table.
Usage: fscheck [--type TYPE] [--warn PCT] [--selftest]"""
import argparse, os, sys

PSEUDO = {"proc", "sysfs", "devpts", "cgroup", "cgroup2", "debugfs", "securityfs",
          "pstore", "autofs", "mqueue", "tracefs", "fusectl", "configfs", "devtmpfs",
          "tmpfs", "overlay", "squashfs"}

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:
                out.append({"dev": p[0], "mp": p[1], "fs": p[2], "opts": p[3]})
    return out

def check(warn=90, only_type=None, include_pseudo=False):
    rows = []
    for m in get_mounts():
        if only_type and m["fs"] != only_type:
            continue
        if not include_pseudo and m["fs"] in PSEUDO:
            continue
        try:
            st = os.statvfs(m["mp"])
        except OSError:
            continue
        total = st.f_blocks * st.f_frsize
        if total == 0:
            continue
        free = st.f_bfree * st.f_frsize
        used = total - free
        pct = used * 100.0 / total
        flags = []
        if "ro" in m["opts"].split(","):
            flags.append("READ-ONLY")
        if pct >= warn:
            flags.append(f"OVER {warn}% FULL")
        rows.append({**m, "total": total, "free": free, "used": used,
                     "pct": pct, "flags": flags})
    return rows

def selftest():
    rows = check()
    ok = True
    if not rows:
        print("FAIL: no filesystems found"); ok = False
    if not any(r["mp"] == "/" for r in rows):
        print("FAIL: root mount missing"); ok = False
    for r in rows:
        if not (0 <= r["pct"] <= 100):
            print(f"FAIL: bad pct for {r['mp']}"); ok = False
    if ok:
        print(f"selftest: PASS ({len(rows)} filesystems, root present, pcts sane)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="fscheck",
        description="Filesystem type, mount options, and free space per mount in one table.")
    ap.add_argument("--type", help="only show this filesystem type (e.g. ext4)")
    ap.add_argument("--warn", type=int, default=90, help="usage %% that triggers a warning (default 90)")
    ap.add_argument("--all", action="store_true", help="include pseudo filesystems")
    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 = check(a.warn, a.type, a.all)
    print(f"{'MOUNT':<24} {'FS':<10} {'SIZE':>9} {'FREE':>9} {'USED%':>6}  OPTIONS / FLAGS")
    for r in rows:
        opts = r["opts"]
        if len(opts) > 34:
            opts = opts[:31] + "..."
        flag = "  !! " + " ".join(r["flags"]) if r["flags"] else ""
        print(f"{r['mp']:<24} {r['fs']:<10} {human(r['total']):>9} {human(r['free']):>9} {r['pct']:>5.1f}%  {opts}{flag}")
    if not rows:
        print("no filesystems matched")
    return 0

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