#!/usr/bin/env python3
"""mountwatch - watch for mount/unmount events by polling /proc/mounts.
Usage: mountwatch [--interval SEC] [--duration SEC] [--selftest]
Polls /proc/mounts and reports mounts that appear or disappear, with a
timestamp. Ctrl-C stops it and prints a summary."""
import argparse, sys, time
from datetime import datetime

def read_mounts():
    mounts = {}
    try:
        with open("/proc/mounts") as f:
            for line in f:
                p = line.split()
                if len(p) >= 3:
                    mounts[p[1]] = (p[0], p[2])
    except OSError:
        pass
    return mounts

def diff_mounts(old, new):
    added = {m: new[m] for m in new if m not in old}
    removed = {m: old[m] for m in old if m not in new}
    changed = {m: (old[m], new[m]) for m in old if m in new and old[m] != new[m]}
    return added, removed, changed

def stamp():
    return datetime.now().strftime("%H:%M:%S")

def selftest():
    a = {"/": ("/dev/sda1", "ext4"), "/data": ("/dev/sdb1", "xfs")}
    b = {"/": ("/dev/sda1", "ext4"), "/mnt/usb": ("/dev/sdc1", "vfat")}
    added, removed, changed = diff_mounts(a, b)
    ok = True
    if "/mnt/usb" not in added:
        print("FAIL: added mount not detected"); ok = False
    if "/data" not in removed:
        print("FAIL: removed mount not detected"); ok = False
    if changed:
        print("FAIL: spurious change detected"); ok = False
    c = {"/": ("/dev/sda1", "ext4"), "/data": ("/dev/sdb1", "ext4")}
    _ad, _rm, ch = diff_mounts(a, c)
    if "/data" not in ch:
        print("FAIL: fs-type change not detected"); ok = False
    # live 1-second poll must run cleanly
    before = read_mounts()
    time.sleep(1)
    after = read_mounts()
    diff_mounts(before, after)
    if not before:
        print("FAIL: no live mounts read"); ok = False
    if ok:
        print("selftest: PASS (added/removed/changed diff logic + 1s live poll)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="mountwatch",
        description="Watch for mount/unmount events by polling /proc/mounts.")
    ap.add_argument("--interval", type=float, default=2, help="poll interval in seconds (default 2)")
    ap.add_argument("--duration", type=float, default=60, help="how long to watch (default 60, 0 = forever)")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    print(f"watching mounts every {a.interval}s"
          f"{' for ' + str(a.duration) + 's' if a.duration else ' until Ctrl-C'} (initial: {len(read_mounts())} mounts)")
    prev = read_mounts()
    start = time.time()
    events = 0
    try:
        while True:
            time.sleep(a.interval)
            cur = read_mounts()
            added, removed, changed = diff_mounts(prev, cur)
            for m, (dev, fs) in sorted(added.items()):
                print(f"[{stamp()}] MOUNTED   {m} ({dev}, {fs})")
                events += 1
            for m, (dev, fs) in sorted(removed.items()):
                print(f"[{stamp()}] UNMOUNTED {m} ({dev}, {fs})")
                events += 1
            for m, (o, n) in sorted(changed.items()):
                print(f"[{stamp()}] CHANGED   {m}: {o[0]}/{o[1]} -> {n[0]}/{n[1]}")
                events += 1
            prev = cur
            if a.duration and time.time() - start >= a.duration:
                break
    except KeyboardInterrupt:
        print("\nstopped by user.")
    print(f"done: {events} mount event(s) in {time.time() - start:.0f}s.")
    return 0

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