#!/bin/sh
# DF-5301 replug driver (host side, QEMU monitor)
# Cycles the emulated external hub (and its two tablet children) so the
# guest runs uhub_attach/uhub_detach on uhub1 repeatedly.
#
# usage: python3 replug.py <cycles> [dwell_add] [dwell_del]
import socket, sys, time

SOCK = "boot-mon.sock"

def mk():
    s = socket.socket(socket.AF_UNIX)
    s.connect(SOCK)
    time.sleep(0.2)
    try: s.recv(65536)
    except Exception: pass
    return s

def cmd(s, c, wait=0.3):
    s.sendall((c + "\n").encode())
    time.sleep(wait)
    s.setblocking(False)
    out = b""
    try:
        while True: out += s.recv(65536)
    except Exception: pass
    s.setblocking(True)
    return out.decode(errors="replace")

def main():
    cycles = int(sys.argv[1]) if len(sys.argv) > 1 else 100
    dadd = float(sys.argv[2]) if len(sys.argv) > 2 else 2.0
    ddel = float(sys.argv[3]) if len(sys.argv) > 3 else 2.0
    s = mk()
    for i in range(cycles):
        cmd(s, "device_del h1", 0.3)
        time.sleep(ddel)
        cmd(s, "device_add usb-hub,id=h1,bus=uhci0.0,port=1", 0.8)
        cmd(s, "device_add usb-tablet,id=ta,bus=uhci0.0,port=1.1", 0.3)
        cmd(s, "device_add usb-tablet,id=tb,bus=uhci0.0,port=1.2", 0.3)
        time.sleep(dadd)
        if i % 10 == 0:
            print("cycle", i, flush=True)
    print("done", cycles, flush=True)

if __name__ == "__main__":
    main()
