#!/usr/bin/env python
import json
import subprocess
import re

ACCOUNTS = ["posteo", "gmail", "xkonni"]
l_acc = max([len(a) for a in ACCOUNTS])
SERVICES = ["mbsync@ykonni", "muchsync@ykonni"]
l_ser = max([len(s) for s in SERVICES])

tooltip="<b>accounts</b>\n"
total = 0

for a in ACCOUNTS:
    cmd = f"notmuch count folder:{a}/Inbox AND tag:unread AND NOT tag:killed"
    ret = subprocess.check_output(cmd, shell=True).decode("UTF-8").replace("\n", "")
    count = int(ret)
    tooltip += f"  - {a:<{l_acc}}: {count}\n"
    total += count

tooltip += "\n<b>services</b>\n"
for s_name in SERVICES:
    cmd = f"/usr/bin/systemctl --user status {s_name}"
    ret = ""
    s_status = ""
    s_time = ""
    try:
        ret = subprocess.run(cmd, capture_output=True, check=False, shell=True)
    except Exception as ex:
        print(ex)
        pass

    s_status = 0
    for line in  ret.stdout.decode("UTF-8").split("\n"):
        if "since" in line:
            m = re.search("[a-z0-9 ]* ago", line)
            if m:
                s_time = m.group(0)
        if ("Process" in line) or ("Main PID" in line):
            m = re.search("status=[0-9]*", line)
            if m:
                tmp = int(m.group(0).replace("status=", ""))
                if not tmp == 0 and not tmp == s_status:
                    s_status = tmp

    tooltip += f"  - {s_name:<{l_ser}}: status={s_status}, {s_time}\n"

text = f"{total}"
alt = "read" if total == 0 else "unread"

j = { "alt": alt, "class": "mail",
    "text": text, "tooltip": tooltip }
print(json.dumps(j))

