#!/usr/bin/python3
# Wombat-Email: turns a plain-text message (headers, blank line, text) on stdin into one with two versions
# of the same text, on stdout: the plain text, and HTML that shows it in a fixed-width font with working
# links. Mail programs that show HTML pick that one; the others keep the plain text. Used by the server's
# own mail (the daily report, quota warnings); the panel does the same in PHP (panel/lib/app.php).
#   ... | wombat-email-mime | /usr/sbin/sendmail ...
import html
import re
import sys
from email import message_from_string, policy
from email.message import EmailMessage

URL = re.compile(r"https?://[^\s<>\"“”‘’]*[^\s<>\"“”‘’.,;:!?)']")
# Kept in step with panel/lib/app.php's mail_html().
PAGE = '<html><body><pre style="white-space: pre-wrap; word-wrap: break-word;">{}</pre></body></html>\n'   # (the mail program's own fixed-width font, size and spacing), but long lines wrap


def as_html(text):
    out, at = [], 0
    for m in URL.finditer(text):
        out.append(html.escape(text[at:m.start()]))
        url = html.escape(m.group(0))
        out.append(f'<a href="{url}">{url}</a>')
        at = m.end()
    out.append(html.escape(text[at:]))
    return PAGE.format("".join(out))


# Headers and text split here, both as UTF-8 (the email parser would take 8-bit text for unknown bytes).
head, _, text = sys.stdin.buffer.read().decode("utf-8", "replace").replace("\r\n", "\n").partition("\n\n")
src = message_from_string(head + "\n\n", policy=policy.default)
msg = EmailMessage(policy=policy.default)
for key, value in src.items():
    if key.lower() not in ("mime-version", "content-type", "content-transfer-encoding"):
        msg[key] = value
msg.set_content(text)
msg.add_alternative(as_html(text), subtype="html")
sys.stdout.buffer.write(msg.as_bytes())
