#!/usr/bin/env python3
# Hulot converter: text/source→text/html (that is, source code to HTML) with highlight
# © Reuben Thomas 2023

import os
import sys
from tempfile import TemporaryDirectory
import subprocess
import re

from mime_convert import converter_to_mimetypes


converter = os.path.basename(sys.argv[0])
(srctype, desttype) = converter_to_mimetypes(converter)

mime_to_ext = {
  "text/x-c": "c",
  "text/x-c++": "cc",
  "text/x-fortran": "f",
  "text/x-makefile": "mak",
  "text/x-pl1": "pl1",
  "text/x-asm": "asm",
  "text/x-pascal": "pas",
  "text/x-java": "java",
  "text/x-bcpl": "b",
  "text/x-m4": "m4",
  "text/x-po": "po",
  "text/x-perl": "pl",
  "text/x-python": "py",
  "text/x-ruby": "rb",
  "text/x-shellscript": "sh",
}
file = sys.argv[1]
with TemporaryDirectory() as tempdir:
    css_file = os.path.join(tempdir, "highlight.css")
    html = subprocess.check_output(["highlight", file, "-c", css_file, "-S", mime_to_ext[srctype]])
    css = open(css_file, 'rb').read()
    re.sub(b"(<body[^>]*>)", b'\\1<style type="text/css">' + css + b'</style>', html)
    sys.stdout.buffer.write(html)
