#!/usr/bin/env python3
# mimedown - generate multipart text and HTML MIME message from Markdown input.

# Requires mistune; install it with pip:
# sudo -H python3 -m pip install mistune

import signal
import sys

import mistune

md2html = None
if 'html' in dir(mistune):
    md2html = mistune.html
elif 'markdown' in dir(mistune):
    md2html = mistune.markdown
else:
    print("mistune install is broken", file=sys.stderr)

def mimedown(infile, outfile):
    text = infile.read()
    html = md2html(text)
    html = "<htm><head><title></title><body>%s</body></html>" % html
    print('''<#multipart type=alternative>
%s
<#part type=text/html>
%s
<#/multipart>
''' % (text, html), file=outfile)

if __name__ == '__main__':
    try:
        mimedown(sys.stdin, sys.stdout)
    except KeyboardInterrupt:
        # https://tldp.org/LDP/abs/html/exitcodes.html
        sys.exit(signal.SIGINT + 128)

