#!/usr/bin/env python3
"""Send a shell command to the guest's serial debug shell and read the reply.

  serial.py "cmd"           run and read for 5s
  serial.py "cmd" 20        run and read for 20s
  serial.py --read 5        read only
"""
import socket, sys, time, os

SCRATCH = os.environ.get(
    "VM_STATE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "state")
)
s = socket.socket(socket.AF_UNIX)
s.connect(os.path.join(SCRATCH, "serial.sock"))
s.settimeout(0.5)


def drain():
    out = b""
    try:
        while True:
            c = s.recv(65536)
            if not c:
                break
            out += c
    except (socket.timeout, BlockingIOError):
        pass
    return out


if sys.argv[1] == "--read":
    time.sleep(float(sys.argv[2]))
    sys.stdout.write(drain().decode(errors="replace"))
    sys.exit()

drain()
cmd = sys.argv[1]
secs = float(sys.argv[2]) if len(sys.argv) > 2 else 5.0
s.sendall(("\n" + cmd + "\n").encode())
end = time.time() + secs
out = b""
while time.time() < end:
    out += drain()
sys.stdout.write(out.decode(errors="replace"))
