#!/usr/bin/python3

import asyncio
import sys
import tempfile


def say(msg):
    print(msg, file=sys.stderr, flush=True)


def main():
    say("Debugging mode enabled")

    # Get the size of the zipfile
    size = int.from_bytes(sys.stdin.buffer.read(4))
    say(f"Reading {size} bytes of Python zipfile")

    # Read the zipfile from stdin
    zf = sys.stdin.buffer.read(size)
    if len(zf) < size:
        say("Client closed the connection early")
        return 1

    with tempfile.NamedTemporaryFile(suffix=".zip") as t:
        say(f"Storing the Python zipfile to {t.name}")
        t.write(zf)
        t.flush()

        say("Importing the conversion module")
        sys.path.insert(0, t.name)

        from dangerzone.conversion.doc_to_pixels import main

        return asyncio.run(main())


if __name__ == "__main__":
    sys.exit(main())
