#!/usr/bin/env python3

import os
import sys
import struct
from subprocess import Popen, PIPE




def main(argv):
    p = Popen(argv[1:], bufsize=0, stdin=PIPE, stdout=PIPE)

    def write(data):
        l = p.stdin.write(data)
        if len(data) != l:
            raise Exception("could not write %d bytes of data (put %d)" % (len(data), l))

    def read(l):
        data = p.stdout.read(l)
        if len(data) != l:
            raise Exception("could not read %d bytes of data (got %d)" % (l, len(data)))
        return data

    def submit(action, data):
        h = struct.pack("<BI", ord(action), len(data))
        write(h)
        write(data)

    def obtain():
        l = read(4)
        (l, ) = struct.unpack("<I", l)
        return read(l)

    if read(14) != b"Hello, World!\n":
        raise Exception("Unexpected output")

    submit('c', b"\0" * 32)
    submit('m', bytes.fromhex("000102030405060708090A0B0C0D0E0F"))
    submit('a', bytes.fromhex("000102030405060708090A0B0C0D0E0F"))
    submit('k', bytes.fromhex("000102030405060708090A0B0C0D0E0F"))
    submit('p', bytes.fromhex("000102030405060708090A0B0C0D0E0F"))
    submit('s', b"") 
    write(b'e')
    write(b'C')
    data = obtain()
    print(data.hex())
    

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