#!/usr/bin/python3 -I
# Run a libfido2 tool under a pty, answering its PIN prompt with a PIN read
# from stdin (the tools only read the PIN from a tty).
import os, pty, sys
pin = sys.stdin.readline().rstrip("\n").encode()
pid, fd = pty.fork()
if pid == 0:
    os.execvp(sys.argv[1], sys.argv[1:])
buf, sent = b"", False
while True:
    try:
        data = os.read(fd, 1024)
    except OSError:
        break
    if not data:
        break
    buf += data
    if not sent and b"PIN" in buf:
        os.write(fd, pin + b"\n")
        sent = True
    elif sent:
        sys.stderr.buffer.write(data)
sys.exit(os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]))
