local inbox = require 'inbox'
local asio_error = require 'asio_error'
local pipe = require 'pipe'
local unix = require 'unix'
local qt = require 'qt6'

local msg = inbox:receive()
local input = pipe.read_stream.new()
input:assign(msg.input)

local data = byte_span.new(0)
while true do
    local buf = byte_span.new(65536)
    local ok, value = pcall(function()
        return input:read_some(buf)
    end)

    if ok then
        data = byte_span.append(data, buf:first(value))
    elseif value == asio_error.misc.eof then
        break
    else
        error(value)
    end
end
input:close()

local output = unix.seqpacket.socket.new()
output:assign(msg.output)

-- This is the only call that invokes Qt's image parsers. The host never parses
-- the untrusted image bytes itself.
local ok, result = pcall(qt.decode_image, data)
if ok then
    local metadata = byte_span.append(string.format(
        'OK\n%d\n%d\n%s', result.width, result.height, result.format))
    output:send_with_fds(metadata, {result.memfd})
    result.memfd:close()
else
    output:send(byte_span.append('ERROR\n', tostring(result)))
end
output:close()
