#!/usr/bin/env python3
"""diskalarm - alert when a mount crosses a usage threshold, with a one-line report.
Usage: diskalarm [--threshold PCT] [--mount MOUNT] [--selftest]
One line per mount: OK or ALARM. Exit code 0 when all mounts are under the
threshold, 1 when any mount alarms. Designed for cron: pipe it to mail or
just check the exit code."""
import argparse, os, sys

def check(threshold, only=None):
    rows = []
    try:
        with open("/proc/mounts") as f:
            mounts = [line.split() for line in f]
    except OSError:
        return rows
    for p in mounts:
        if len(p) < 3:
            continue
        mp, fs = p[1], p[2]
        if only and mp not in only:
            continue
        if fs in ("proc", "sysfs", "devpts", "cgroup", "cgroup2", "debugfs",
                  "securityfs", "pstore", "autofs", "mqueue", "tracefs", "tmpfs"):
            continue
        try:
            st = os.statvfs(mp)
        except OSError:
            continue
        total = st.f_blocks * st.f_frsize
        if total == 0:
            continue
        free = st.f_bfree * st.f_frsize
        pct = 100.0 * (total - free) / total
        rows.append({"mp": mp, "fs": fs, "pct": pct,
                     "free": free, "alarm": pct >= threshold})
    return rows

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 selftest():
    ok = True
    # threshold 0 must alarm on every real mount; 100 must alarm on none
    # (unless a mount is literally 100% full, which would itself be the alarm)
    all_rows = check(0)
    if not all_rows:
        print("FAIL: no mounts found"); ok = False
    elif not all(r["alarm"] for r in all_rows):
        print("FAIL: threshold 0 did not alarm everywhere"); ok = False
    rows100 = check(100)
    if any(r["alarm"] for r in rows100):
        full = [r["mp"] for r in rows100 if r["alarm"]]
        print(f"note: mount(s) at 100%: {full} (alarm is correct there)")
    rows90 = check(90)
    for r in rows90:
        if not (0 <= r["pct"] <= 100):
            print(f"FAIL: bad pct for {r['mp']}"); ok = False
    if ok:
        print(f"selftest: PASS ({len(all_rows)} mount(s) checked; threshold logic verified)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="diskalarm",
        description="Alert when a mount crosses a usage threshold, with a one-line report.")
    ap.add_argument("--threshold", type=float, default=90,
                    help="usage %% that triggers an alarm (default 90)")
    ap.add_argument("--mount", action="append", help="only check this mount (repeatable)")
    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.threshold, a.mount)
    if not rows:
        print("diskalarm: no mounts to check.")
        return 0
    alarmed = 0
    for r in rows:
        state = "ALARM" if r["alarm"] else "OK"
        if r["alarm"]:
            alarmed += 1
        print(f"{state} {r['mp']} {r['pct']:.1f}% used, {human(r['free'])} free "
              f"(threshold {a.threshold:g}%)")
    if alarmed:
        print(f"diskalarm: {alarmed} mount(s) over {a.threshold:g}% - free space now!")
        return 1
    print(f"diskalarm: all {len(rows)} mount(s) under {a.threshold:g}%.")
    return 0

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