. "$BST_LIB"
require picocom picocom/present

# picocom --help prints the version banner and its compiled-in options, then
# exits 0. USE_FLOCK is the load-bearing one: the upstream Makefile enables
# flock(2) locking and leaves UUCP_LOCK_DIR undefined, so picocom locks its port
# with flock alone -- it cannot open any port at all unless flock(2) works.
check_out picocom/version   "picocom v2023-04"     picocom --help
check_out picocom/use-flock "USE_FLOCK is enabled" picocom --help

# The full device path, non-interactively: --exit opens the port, takes the
# flock, applies raw termios and reads the modem lines, then exits without
# entering the interactive loop (it closes stdin, so no tty is needed here).
# A pty master stands in for a serial port. This is the path that fails with
# "cannot lock ...: Function not implemented" on a kernel without flock(2).
check picocom/pty-exit sh -c 'picocom -X -b 115200 /dev/ptmx'

# The wasm32 serial device. The driver registers /dev/ttySER0 on every image but
# refuses open() with -ENODEV until a host WebSerial port attaches -- the grant
# boundary. Unattended, that refusal is the correct outcome, not a failure.
if [ -c /dev/ttySER0 ]; then
    bst_ok picocom/ttyser-present
    out=$(picocom -X /dev/ttySER0 2>&1); rc=$?
    case "$out" in
        *"No such device"*)
            bst_skip picocom/ttyser-open \
                "no host serial port attached (-ENODEV); browser attach is linux-in-the-browser#60 M2" ;;
        *)
            if [ "$rc" -eq 0 ]; then bst_ok picocom/ttyser-open
            else bst_notok picocom/ttyser-open "rc=$rc $(_bst_1line "$out")"; fi ;;
    esac
else
    bst_skip picocom/ttyser-present "/dev/ttySER0 absent on this kernel"
    bst_skip picocom/ttyser-open    "/dev/ttySER0 absent on this kernel"
fi
