#!/usr/bin/env python3
"""Stub for gamescopectl: `screenshot FILE` writes a small PNG, as gamescope does
(asynchronously on the Frame, which server.SCREENSHOT waits out)."""
import struct
import sys
import zlib

sys.path.insert(0, '/usr/local/lib/fakeframe')
import fakeframe_state as fs  # noqa: E402

args = sys.argv[1:]
fs.log('gamescopectl', args=args)
if len(args) != 2 or args[0] != 'screenshot':
    sys.exit(f'gamescopectl stub: unsupported {args}')


def chunk(kind, data):
    return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))


w, h = 64, 36
rows = b''.join(b'\0' + b''.join(bytes((x * 4, y * 7, 160)) for x in range(w)) for y in range(h))
png = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 2, 0, 0, 0))
       + chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b''))
with open(args[1], 'wb') as f:
    f.write(png)
