#! /usr/bin/python3

import argparse
import contextlib
import pathlib
import shutil
import subprocess
import sys


def run(*args):
    try:
        subprocess.run(
            args,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            check=True,
        )
    except subprocess.CalledProcessError as exc:
        sys.stderr.buffer.write(exc.output)
        raise


parser = argparse.ArgumentParser()
parser.add_argument("--size", default=256, type=int)
parser.add_argument("input")
parser.add_argument("output")
args = parser.parse_args()

fin = pathlib.Path(args.input)
fout = pathlib.Path(fin.with_suffix(".png").name)

lohome = "/tmp/libreoffice"

try:
    run(
        "libreoffice",
        "-env:UserInstallation=file://" + str(lohome),
        "--headless",
        "--convert-to",
        "png",
        str(fin),
    )

    assert fout.exists()

    run(
        "glycin-thumbnailer",
        *["--input", "file://" + str(fout)],
        *["--output", str(args.output)],
        *["--size", str(args.size)],
    )
finally:
    with contextlib.suppress(FileNotFoundError):
        shutil.rmtree(lohome)

    with contextlib.suppress(FileNotFoundError):
        fout.unlink()
