#! /usr/bin/python3

import argparse
import contextlib
import os
import posixpath
import subprocess
import sys
import xml.etree.ElementTree
import zipfile

TYPE_REL = "http://schemas.openxmlformats.org/package/2006/relationships"
TYPE_THUMB = TYPE_REL + "/metadata/thumbnail"


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()

tmp = ""
ns = {
    "rel": TYPE_REL,
}

try:
    with zipfile.ZipFile(args.input) as zf:
        with zf.open("_rels/.rels") as rels:
            et = xml.etree.ElementTree.parse(rels)
            for child in et.findall("rel:Relationship", ns):
                if child.get("Type") == TYPE_THUMB:
                    target = child.get("Target")
                    tmp = zf.extract(target.lstrip(posixpath.sep))
                    break

    if tmp:
        run(
            "glycin-thumbnailer",
            *["--input", "file://" + tmp],
            *["--output", str(args.output)],
            *["--size", str(args.size)],
        )
finally:
    with contextlib.suppress(FileNotFoundError):
        if tmp:
            os.unlink(tmp)
