#!/usr/bin/env python3
"""quota - disk quota usage when set, otherwise free space.
Usage: quota [--user USER] [--selftest]
Reports quota(1) output when quotas exist; otherwise falls back to the
effective limit every user actually has: free space per filesystem, plus
any usrquota/grpquota mount options found in /proc/mounts."""
import argparse, os, shutil, subprocess, 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 system_quota(user=None):
    """Run quota(1) if present. Returns (output, found_any)."""
    if not shutil.which("quota"):
        return None, False
    cmd = ["quota", "-v"]
    if user:
        cmd.append(user)
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        return None, False
    out = (r.stdout + r.stderr).strip()
    if not out or "no quotas" in out.lower() or "Disk quotas for" not in out:
        return out or None, False
    return out, True

def fallback():
    rows = []
    try:
        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(",")
                if fs in ("proc", "sysfs", "devpts", "cgroup", "cgroup2", "tmpfs",
                          "devtmpfs", "overlay"):
                    continue
                try:
                    st = os.statvfs(mp)
                except OSError:
                    continue
                total = st.f_blocks * st.f_frsize
                if total == 0:
                    continue
                free = st.f_bavail * st.f_frsize
                qopts = [o for o in opts if "quota" in o]
                rows.append({"mp": mp, "fs": fs, "total": total, "free": free,
                             "qopts": qopts})
    except OSError:
        pass
    return rows

def selftest():
    rows = fallback()
    ok = True
    if not rows:
        print("FAIL: fallback found no filesystems"); ok = False
    if not any(r["mp"] == "/" for r in rows):
        print("FAIL: root missing from fallback"); ok = False
    for r in rows:
        if r["free"] < 0 or r["free"] > r["total"]:
            print(f"FAIL: bad free space for {r['mp']}"); ok = False
    out, found = system_quota()
    # system quota may or may not exist; either way the call must not crash
    if ok:
        print(f"selftest: PASS (fallback covers {len(rows)} filesystems; system quota: "
              f"{'present' if found else 'absent, fallback used'})")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="quota",
        description="Disk quota usage when set, otherwise free space.")
    ap.add_argument("--user", help="user to query (default: current user)")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    out, found = system_quota(a.user)
    if found:
        print(out)
        return 0
    print("No disk quotas are enforced on this system.")
    print("Effective limit = free space per filesystem:\n")
    print(f"{'MOUNT':<24} {'FS':<10} {'SIZE':>9} {'FREE':>9} {'FREE%':>6}  QUOTA OPTS")
    for r in fallback():
        pct = 100.0 * r["free"] / r["total"]
        qo = ",".join(r["qopts"]) if r["qopts"] else "-"
        print(f"{r['mp']:<24} {r['fs']:<10} {human(r['total']):>9} {human(r['free']):>9} {pct:>5.1f}%  {qo}")
    return 0

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