#!/usr/bin/python3 -I
"""Wombat-Email: the message shown when you log in over SSH (installed by installer/10-base.sh as
/etc/update-motd.d/01-wombat-email). Ubuntu runs it as root at each login, so it only reads local
files and asks nothing of the network. What needs attention and the updates come from status.json
(the daily report and the panel's checks write it), so this says the same as the panel."""
import json, os, shutil, subprocess, sys, time

sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share

BOLD, AMBER, DIM, END = "\033[1m", "\033[33m", "\033[2m", "\033[0m"


def read(path, default=""):
    try:
        with open(path) as f:
            return f.read().strip()
    except OSError:
        return default


def load(path):
    try:
        with open(path) as f:
            return json.load(f)
    except (OSError, ValueError):
        return {}


def size(n):
    return f"{n / 2**30:.1f} GB" if n >= 2**30 else f"{n / 2**20:.0f} MB"   # Ubuntu's own way: 1 GB = 1024 MB


def ago(t):
    s = max(0, int(time.time() - t))
    if s < 3600:
        return f"{s // 60} min ago"
    if s < 172800:
        return f"{s // 3600} h ago"
    return f"{s // 86400} days ago"


def run(*cmd):
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=3).stdout
    except (OSError, subprocess.SubprocessError):
        return ""


settings = we.settings()
host = settings.get("HOSTNAME", os.uname().nodename)
version = read("/opt/wombat-email/VERSION", "?")
osr = dict(l.split("=", 1) for l in read("/etc/os-release").splitlines() if "=" in l)

up = int(float(read("/proc/uptime", "0").split()[0]))
days, hours, mins = up // 86400, up % 86400 // 3600, up % 3600 // 60
uptime = (f"{days} day{'s' * (days != 1)}, " if days else "") + (f"{hours} h" if days or hours else f"{mins} min")

mem = {l.split(":")[0]: int(l.split()[1]) * 1024 for l in read("/proc/meminfo").splitlines() if l.split()[1:2]}
mem_used = 1 - mem.get("MemAvailable", 0) / max(mem.get("MemTotal", 1), 1)
swap_total = mem.get("SwapTotal", 0)
swap = f"{(1 - mem.get('SwapFree', 0) / swap_total) * 100:.0f}% of {size(swap_total)}" if swap_total else "none"
disk = shutil.disk_usage("/")
load1 = read("/proc/loadavg", "0").split()[0]
procs = sum(1 for d in os.listdir("/proc") if d.isdigit())
# Ubuntu 26.04 keeps no utmp, so `who` is empty: count the terminals people are logged in on instead.
# This runs before the new login gets its own terminal, so it counts everyone else; plus one for you.
users = sum(1 for d in os.listdir("/dev/pts") if d.isdigit()) + 1
queue = sum(1 for l in run("postqueue", "-j").splitlines() if l.strip())
ips = {}
for l in run("ip", "-o", "addr", "show", "scope", "global").splitlines():
    p = l.split()
    fam = "IPv4" if p[2] == "inet" else "IPv6"
    ips.setdefault(fam, p[3].split("/")[0])

left = [("Load", f"{load1} ({os.cpu_count()} CPU)"), ("Disk /", f"{disk.used / disk.total * 100:.1f}% of {size(disk.total)}"),
        ("Processes", str(procs)), ("Mail queue", str(queue))]
right = [("Memory", f"{mem_used * 100:.0f}% of {size(mem.get('MemTotal', 0))}"), ("Swap", swap),
         ("Logged in", str(users)), ("", "")]

# The postman, drawn in text: each line is (text, 256-color) pieces, centered on one column; the
# letter flies in on the left, the mailbag hangs on the right, the name sits beside the face.
# Colors chosen to read on dark and light terminals alike.
SKY, PAPER, STAMP, CAP, BRASS, VISOR, FUR, EYE, MUZZLE, NOSE, VEST, BAG = 39, 249, 160, 33, 220, 31, 137, 94, 180, 241, 25, 172
LOGO = [
    [(".-'''''''''-.", CAP)],
    [("/   ", CAP), (".-----.", BRASS), ("   \\", CAP)],
    [(".-.  ", FUR), ("/____", CAP), ("| [=] |", BRASS), ("____\\", CAP), ("  .-.", FUR)],
    [("( (  ", FUR), ("'================='", VISOR), ("  ) )", FUR)],
    [("'-|    ", FUR), ("(o)", EYE), ("       ", FUR), ("(o)", EYE), ("    |-'", FUR)],
    [("|      ", FUR), (".-------.", MUZZLE), ("      |", FUR)],
    [("|     ", FUR), ("( ", MUZZLE), ("#######", NOSE), (" )", MUZZLE), ("     |", FUR)],
    [("\\     ", FUR), ("'--\\_/--'", MUZZLE), ("     /", FUR)],
    [(".--'-.", FUR), ("_____________", MUZZLE), (".-'--.", FUR)],
    [("/ ", VEST), ("o", BRASS), ("   \\\\", VEST), (" ", VEST), ("'-------'", MUZZLE), (" ", VEST), ("//     \\", VEST)],
    [("/__", VEST), ("o", BRASS), ("___\\\\", VEST), ("___________", VEST), ("//______\\", VEST)],
]
LEFT = {0: [(" ==  ", SKY), (".----.", PAPER)], 1: [("===  ", SKY), ("|", PAPER), ("\\__/", STAMP), ("|", PAPER)],
        2: [("     ", SKY), ("'----'", PAPER)]}
RIGHT = {8: [("   .------.", BAG)], 9: [("  |", BAG), ("[====]", BRASS), ("|", BAG)], 10: [(" '------'", BAG)]}
BESIDE = {4: f"{BOLD}Wombat-Email{END} v{version}", 5: host}


def logo():
    for i, pieces in enumerate(LOGO):
        left = LEFT.get(i, [])
        start = 26 - sum(len(t) for t, _ in pieces) // 2
        line = left + [(" " * (start - sum(len(t) for t, _ in left)), 0)] + pieces + RIGHT.get(i, [])
        text = "".join(f"\033[38;5;{c}m{t}{END}" if t.strip() else t for t, c in line)
        width = sum(len(t) for t, _ in line)
        print(f"  {text}" + (" " * (47 - width) + BESIDE[i] if i in BESIDE else ""))


print()
logo()
print()
print(f"  {DIM}{osr.get('PRETTY_NAME', 'Ubuntu').strip(chr(34))} (kernel {os.uname().release}), up {uptime}, {time.strftime('%a %b %-d %H:%M %Z')}{END}")
print()
for (a, b), (c, d) in zip(left, right):
    print(f"  {a:<11}{b:<24}{c:<11}{d}".rstrip())
for fam in ("IPv4", "IPv6"):
    if fam in ips:
        print(f"  {fam:<11}{ips[fam]}")
print()

st = load("/var/lib/wombat-email/status.json")
attention = st.get("attention") or []
as_of = f" {DIM}(checked {ago(st['checked'])}){END}" if st.get("checked") else ""
if attention:
    print(f"  {AMBER}Needs attention:{END}{as_of}")
    for a in attention:
        print(f"    - {a}")
elif st:
    print(f"  Needs attention: nothing{as_of}")
u = st.get("updates") or {}
if u.get("pending"):
    print(f"  Updates: {u['pending']} waiting, {u.get('security', 0)} security (those install by themselves)")
elif st:
    print("  Updates: none waiting")
if os.path.exists("/var/run/reboot-required"):
    print(f"  {AMBER}A restart is needed:{END} Restart the server, in the panel's Settings")

b = load("/var/lib/wombat-email/backup-status.json")
where = read("/var/lib/wombat-email/backup-where") or ("off this server" if settings.get("BACKUP_REPO", "").startswith(("rclone:", "s3:", "sftp:", "rest:", "b2:", "azure:", "gs:", "swift:")) else "on this server only")
if b.get("finished"):
    state = "ok" if b.get("state") == "ok" else f"{AMBER}{b.get('message', 'failed')}{END}"
    print(f"  Last backup: {ago(b['finished'])}, {state} ({where})")
else:
    print("  Last backup: none yet")
print(f"  Panel: https://{host}/panel/")
print()
