#!/usr/bin/python3
# Hulot converter: text/x-tex→application/pdf
# © Reuben Thomas 2002-2023

import os
import sys
from pathlib import Path
from tempfile import TemporaryDirectory, mkdtemp
import subprocess

file = Path(os.path.abspath(sys.argv[1]))
with TemporaryDirectory() as tempdir:
    os.chdir(tempdir)
    env = dict(os.environ)
    env["TEXMFDBS"] = os.path.join(os.environ['HOME'], "texmf") + os.pathsep
    env["TEXINPUTS"] = str(file.parent) + os.pathsep
    env["BIBINPUTS"] = str(file.parent) + os.pathsep
    output = subprocess.check_output(
        ["latexmk", "--verbose", "-f", str(file)],
        env = env,
    )
    sys.stdout.buffer.write(open(os.path.join(tempdir, file.with_suffix(".pdf").name), 'rb').read())
