#!/usr/bin/env python3
# motd - generate a message of the day from live system stats plus a quote
# Usage: motd [--quote-only] [--no-quote]
import argparse, datetime, os, random, shutil, sys

QUOTES = [
 "The best time to plant a tree was twenty years ago. The second best time is now.",
 "First, solve the problem. Then, write the code.",
 "Simplicity is the soul of efficiency.",
 "Done is better than perfect.",
 "Slow is smooth, and smooth is fast.",
 "A journey of a thousand miles begins with a single step.",
 "Measure twice, cut once.",
 "Ship it, then make it better.",
]

def _read(path):
    try:
        with open(path) as f:
            return f.read()
    except OSError:
        return ""

def stats():
    s = {}
    try:
        with open("/proc/uptime") as f:
            s["uptime_s"] = float(f.read().split()[0])
    except OSError:
        s["uptime_s"] = 0.0
    try:
        with open("/proc/loadavg") as f:
            s["load"] = f.read().split()[:3]
    except OSError:
        s["load"] = ["?", "?", "?"]
    mem_total = mem_avail = 0
    for line in _read("/proc/meminfo").splitlines():
        k, _, v = line.partition(":")
        if k.strip() == "MemTotal":
            mem_total = int(v.split()[0])
        elif k.strip() == "MemAvailable":
            mem_avail = int(v.split()[0])
    s["mem_total_kb"] = mem_total
    s["mem_avail_kb"] = mem_avail
    du = shutil.disk_usage("/")
    s["disk_total"] = du.total
    s["disk_free"] = du.free
    s["cpus"] = os.cpu_count() or 1
    try:
        s["users"] = len(os.listdir("/home")) if os.path.isdir("/home") else 0
    except OSError:
        s["users"] = 0
    return s

def fmt_bytes(n):
    for unit in ("B", "KB", "MB", "GB", "TB"):
        if n < 1024:
            return f"{n:.1f} {unit}"
        n /= 1024
    return f"{n:.1f} PB"

def fmt_uptime(sec):
    d, sec = divmod(int(sec), 86400)
    h, sec = divmod(sec, 3600)
    m, sec = divmod(sec, 60)
    parts = []
    if d:
        parts.append(f"{d}d")
    if h:
        parts.append(f"{h}h")
    if m:
        parts.append(f"{m}m")
    parts.append(f"{sec}s")
    return " ".join(parts)

def build():
    now = datetime.datetime.now()
    s = stats()
    mem_used_pct = 0.0
    if s["mem_total_kb"]:
        mem_used_pct = 100.0 * (1 - s["mem_avail_kb"] / s["mem_total_kb"])
    disk_used_pct = 100.0 * (1 - s["disk_free"] / s["disk_total"]) if s["disk_total"] else 0.0
    quote = random.Random(now.strftime("%Y-%m-%d")).choice(QUOTES)
    lines = [
        f"  Welcome — {now.strftime('%A, %B %d, %Y  %H:%M')}",
        f"  Uptime: {fmt_uptime(s['uptime_s'])}   Load: {' '.join(s['load'])}   CPUs: {s['cpus']}",
        f"  Memory: {mem_used_pct:.0f}% used ({fmt_bytes(s['mem_total_kb'] * 1024)} total)",
        f"  Disk /: {disk_used_pct:.0f}% used ({fmt_bytes(s['disk_free'])} free of {fmt_bytes(s['disk_total'])})",
        f"  Quote of the day: \"{quote}\"",
    ]
    return "\n".join(lines)

def selftest():
    out = build()
    assert "Uptime" in out and "Load" in out and "Quote" in out, out
    assert fmt_uptime(90061) == "1d 1h 1m 1s"
    assert fmt_bytes(2048) == "2.0 KB"
    print(out)
    print("motd selftest OK")

def main():
    p = argparse.ArgumentParser(description="Generate a message of the day from live system stats plus a quote.")
    p.add_argument("--quote-only", action="store_true", help="print only the quote of the day")
    p.add_argument("--no-quote", action="store_true", help="omit the quote line")
    p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    a = p.parse_args()
    if a.selftest:
        selftest(); return 0
    if a.quote_only:
        now = datetime.datetime.now()
        print(random.Random(now.strftime("%Y-%m-%d")).choice(QUOTES))
        return 0
    out = build()
    if a.no_quote:
        out = "\n".join(l for l in out.splitlines() if "Quote" not in l)
    print(out)
    return 0

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