#!/usr/bin/env python3
"""rpapi.py: the reference client for RPAPI 1, RETRO-PORT's serial API.

A library (class RPAPI) and a command-line tool, standard library only. It
talks to a RETRO-PORT over a serial port, or to a retro-ports server's raw
TCP port. The spec is rpapi-spec.txt beside this file
(http://n9taxretrolab.net/api/).

  rpapi.py --serial /dev/ttyUSB0 --baud 9600 dir /
  rpapi.py --serial /dev/ttyUSB0 get /DOWNLOAD/ZORK1.ZIP
  rpapi.py --serial /dev/ttyUSB0 put game.com /GAMES/GAME.COM
  rpapi.py --tcp pi.local:2001 fetch http://example.com/file.zip
  rpapi.py --serial /dev/ttyUSB0 shell        (type commands yourself)
  rpapi.py --serial /dev/ttyUSB0 test         (the conformance test)

Commands: dir [path] | get remote [local] | put local [remote] | fetch url
[path] | del path | mkdir dir | ren old new | stat path | free | time |
status | xget remote [local] | xput local [remote] | shell | test
"""
import argparse, os, random, socket, sys, time

WAKE = b"\x16\x16RPAPI\r"


def crc16(data, crc=0):
    """CRC-16/XMODEM: polynomial 0x1021, initial value 0."""
    for b in data:
        crc ^= b << 8
        for _ in range(8):
            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
    return crc


class ApiError(Exception):
    def __init__(self, code, text):
        super().__init__("ER %d %s" % (code, text))
        self.code, self.text = code, text


# ---------------------------------------------------------------- transports

class TcpLink:
    def __init__(self, hostport):
        host, port = hostport.rsplit(":", 1)
        self.s = socket.create_connection((host, int(port)), timeout=10)

    def write(self, b):
        self.s.sendall(b)

    def read(self, n, timeout):
        self.s.settimeout(max(timeout, 0.001))
        try:
            return self.s.recv(n)
        except socket.timeout:
            return b""

    def close(self):
        self.s.close()


class SerialLink:
    """A serial port through termios: 8N1, no flow control, raw."""
    def __init__(self, dev, baud):
        import termios, tty
        self.fd = os.open(dev, os.O_RDWR | os.O_NOCTTY)
        tty.setraw(self.fd)
        a = termios.tcgetattr(self.fd)
        speed = getattr(termios, "B%d" % baud)
        a[2] = (a[2] & ~(termios.CSIZE | termios.PARENB | termios.CSTOPB | getattr(termios, "CRTSCTS", 0))) \
            | termios.CS8 | termios.CLOCAL | termios.CREAD
        a[0] &= ~(termios.IXON | termios.IXOFF | termios.IXANY)
        a[4] = a[5] = speed
        termios.tcsetattr(self.fd, termios.TCSANOW, a)
        termios.tcflush(self.fd, termios.TCIOFLUSH)

    def write(self, b):
        while b:
            n = os.write(self.fd, b)
            b = b[n:]

    def read(self, n, timeout):
        import select
        r, _, _ = select.select([self.fd], [], [], max(timeout, 0))
        return os.read(self.fd, n) if r else b""

    def close(self):
        os.close(self.fd)


# ---------------------------------------------------------------- the protocol

class RPAPI:
    def __init__(self, link, verbose=False):
        self.link, self.buf, self.verbose = link, b"", verbose
        self.block = 1024
        self.hex = False

    # -- bytes and lines
    def _fill(self, deadline):
        got = self.link.read(4096, deadline - time.time())
        self.buf += got
        return bool(got)

    def read_exact(self, n, timeout=15):
        deadline = time.time() + timeout
        while len(self.buf) < n:
            if time.time() > deadline:
                raise TimeoutError("timed out waiting for %d bytes" % n)
            self._fill(deadline)
        out, self.buf = self.buf[:n], self.buf[n:]
        return out

    def read_line(self, timeout=15):
        """One line, CR/LF stripped. Empty lines are skipped (the spec says to)."""
        deadline = time.time() + timeout
        while True:
            i = self.buf.find(b"\n")
            if i >= 0:
                ln, self.buf = self.buf[:i], self.buf[i + 1:]
                ln = ln.rstrip(b"\r").decode("latin-1")
                if self.verbose:
                    print("<", ln, file=sys.stderr)
                if ln.strip():
                    return ln
                continue
            if time.time() > deadline:
                raise TimeoutError("no reply")
            self._fill(deadline)

    def send(self, s):
        if self.verbose:
            print(">", s, file=sys.stderr)
        self.link.write(s.encode("latin-1") + b"\r")

    # -- getting in
    def wake(self, tries=4, wait=3.0):
        """Send the wake string until the sign-on comes back. Anything before it
        (a menu being redrawn, the screen saver ending) is skipped."""
        for _ in range(tries):
            self.buf = b""
            self.link.write(WAKE)
            deadline = time.time() + wait
            while time.time() < deadline:
                try:
                    ln = self.read_line(deadline - time.time())
                except TimeoutError:
                    break
                if ln.startswith("OK RPAPI "):
                    return self.sync()
        raise TimeoutError("RETRO-PORT didn't answer the wake string")

    def sync(self):
        """HELLO with a word of our own: the reply that ends with it is ours, so
        a second sign-on still on its way (a wake answered late) is skipped."""
        tag = "S%d" % random.randrange(10000, 99999)
        self.send("HELLO " + tag)
        while True:
            ln = self.read_line(10)
            if ln.startswith("OK RPAPI ") and ln.endswith(" " + tag):
                return self._signon(ln[:-len(tag) - 1])

    def _signon(self, ln):
        words = ln.split()
        self.version = int(words[2])
        for w in words:
            if w.startswith("BLOCK="):
                self.block = int(w[6:])
        self.hex = False
        return ln

    # -- commands
    def cmd(self, line, timeout=30, progress=None):
        """Send a command; return (status words after OK, data lines). Raises ApiError."""
        self.send(line)
        data = []
        while True:
            ln = self.read_line(timeout)
            if ln.startswith("= "):
                data.append(ln[2:])
                if progress:
                    progress(ln[2:])
            elif ln == "OK" or ln.startswith("OK "):
                return ln[3:], data
            elif ln.startswith("ER "):
                code, _, text = ln[3:].partition(" ")
                raise ApiError(int(code), text)
            elif ln == "GO" or ln.startswith("DATA "):
                return ln, data
            # anything else is noise from before the session: skip it

    def hello(self):
        return self.sync()

    def mode(self, hexmode):
        self.cmd("MODE HEX" if hexmode else "MODE BIN")
        self.hex = hexmode

    def _block_in(self, n):
        if not self.hex:
            return self.read_exact(n)
        out = bytearray()
        while len(out) < n:
            out += bytes.fromhex(self.read_line())
        return bytes(out)

    def read(self, h, offset, count, retries=3):
        """READ: bytes at offset (b"" at the end). Retries on a bad CRC."""
        for _ in range(retries):
            st, _ = self.cmd("READ %d %d %d" % (h, offset, count))
            if not st.startswith("DATA "):
                raise ApiError(0, "expected DATA, got " + st)
            _, n, crc = st.split()
            d = self._block_in(int(n))
            if crc16(d) == int(crc, 16):
                return d
        raise ApiError(412, "block kept arriving damaged")

    def write(self, h, offset, data, retries=3):
        """WRITE: data at offset; returns the new file size."""
        for _ in range(retries):
            st, _ = self.cmd("WRITE %d %d %d %04X" % (h, offset, len(data), crc16(data)))
            if not data:
                return int(st)
            if st != "GO":
                raise ApiError(0, "expected GO, got " + st)
            if self.hex:
                hx = data.hex().upper()
                self.link.write(b"".join(hx[i:i + 64].encode() + b"\r\n" for i in range(0, len(hx), 64)))
            else:
                self.link.write(data)
            try:
                return int(self.cmd_status()[0])
            except ApiError as e:
                if e.code != 412:
                    raise
        raise ApiError(412, "block kept arriving damaged")

    def cmd_status(self, timeout=30):
        """The status line that ends a command whose data has just gone out."""
        while True:
            ln = self.read_line(timeout)
            if ln == "OK" or ln.startswith("OK "):
                return ln[3:], []
            if ln.startswith("ER "):
                code, _, text = ln[3:].partition(" ")
                raise ApiError(int(code), text)

    def open(self, path, mode):
        st, _ = self.cmd('OPEN "%s" %s' % (path, mode))
        h, size = st.split()
        return int(h), int(size)

    def close(self, h=None):
        self.cmd("CLOSE" if h is None else "CLOSE %d" % h)

    def dir(self, path="", start=None, count=None):
        """[(type, size, date, time, short, name)], more"""
        c = 'DIR "%s"' % path if path else "DIR"
        if start is not None:
            if not path:
                c = "DIR ."
            c += " %d" % start + (" %d" % count if count is not None else "")
        st, lines = self.cmd(c)
        return [parse_entry(l) for l in lines], st.endswith("MORE")

    def stat(self, path):
        return parse_entry(self.cmd('STAT "%s"' % path)[0])

    # -- whole files
    def get(self, remote, local, block=None, progress=None):
        block = min(block or self.block, self.block)
        h, size = self.open(remote, "R")
        try:
            with open(local, "wb") as f:
                off = 0
                while True:
                    d = self.read(h, off, block)
                    if not d:
                        break
                    f.write(d)
                    off += len(d)
                    if progress:
                        progress(off, size)
        finally:
            self.close(h)
        return off

    def put(self, local, remote, block=None, progress=None, resume=False):
        block = min(block or self.block, self.block)
        h, size = self.open(remote, "A" if resume else "W")
        try:
            with open(local, "rb") as f:
                f.seek(size if resume else 0)
                off = size if resume else 0
                total = os.path.getsize(local)
                while True:
                    d = f.read(block)
                    if not d:
                        break
                    self.write(h, off, d)
                    off += len(d)
                    if progress:
                        progress(off, total)
        finally:
            self.close(h)
        return off


def parse_entry(s):
    t, size, date, tm, short, name = s.split(" ", 5)
    return t, int(size), date, tm, short, name


# ---------------------------------------------------------------- XMODEM (for XGET / XPUT)

SOH, STX, EOT, ACK, NAK, CAN = 1, 2, 4, 6, 0x15, 0x18


def xmodem_receive(api, timeout=60):
    """XMODEM-CRC / 1K receiver; returns the data (with the sender's padding)."""
    out, expect, started = bytearray(), 1, False
    deadline = time.time() + timeout
    while True:
        if not started:                       # repeat the C until the first block comes
            api.link.write(b"C")
        try:
            h = api.read_exact(1, 3 if not started else max(1, deadline - time.time()))[0]
        except TimeoutError:
            if started or time.time() > deadline:
                raise ApiError(504, "no XMODEM data")
            continue
        started = True
        if h == EOT:
            api.link.write(bytes([ACK]))
            return bytes(out)
        if h == CAN:
            raise ApiError(499, "sender cancelled")
        if h not in (SOH, STX):
            continue
        n = 128 if h == SOH else 1024
        pkt = api.read_exact(2 + n + 2, 10)
        blk, inv, d, crc = pkt[0], pkt[1], pkt[2:2 + n], pkt[2 + n] << 8 | pkt[3 + n]
        if blk ^ inv != 0xFF or crc16(d) != crc:
            api.link.write(bytes([NAK]))
            continue
        if blk == expect & 0xFF:
            out += d
            expect += 1
        api.link.write(bytes([ACK]))


def xmodem_send(api, data, timeout=60):
    """XMODEM sender: 128-byte blocks, CRC or checksum as the receiver asks."""
    deadline = time.time() + timeout
    while True:
        c = api.read_exact(1, max(1, deadline - time.time()))[0]
        if c in (ord("C"), NAK):
            use_crc = c == ord("C")
            break
    blocks = [data[i:i + 128] for i in range(0, len(data), 128)] or [b""]
    for i, d in enumerate(blocks, 1):
        d = d.ljust(128, b"\x1a")
        tail = crc16(d).to_bytes(2, "big") if use_crc else bytes([sum(d) & 0xFF])
        pkt = bytes([SOH, i & 0xFF, 0xFF - (i & 0xFF)]) + d + tail
        for _ in range(10):
            api.link.write(pkt)
            r = api.read_exact(1, 10)[0]
            if r == ACK:
                break
            if r == CAN:
                raise ApiError(499, "receiver cancelled")
        else:
            raise ApiError(504, "block %d not acknowledged" % i)
    for _ in range(10):
        api.link.write(bytes([EOT]))
        if api.read_exact(1, 10)[0] == ACK:
            return


# ---------------------------------------------------------------- the conformance test

def run_test(api, offline=False, slow=False):
    """Exercise every command against a scratch folder /RPAPITST; True if all pass."""
    fails = []

    def check(name, cond, detail=""):
        print("%-44s %s%s" % (name, "ok" if cond else "FAIL", "" if cond else "  " + str(detail)))
        if not cond:
            fails.append(name)

    def expect_er(name, code, fn):
        try:
            fn()
            check(name, False, "no error")
        except ApiError as e:
            check(name, e.code == code, e)

    st, data = api.cmd("STATUS")
    check("STATUS has VERSION and CARD", any(d.startswith("VERSION ") for d in data)
          and any(d.startswith("CARD ") for d in data), data)
    try:
        t = api.cmd("TIME")[0]
        check("TIME format", len(t) >= 27 and t[4] == "-" and t[13] == ":" and t[20] in "0123456" and t[22] in "+-", t)
    except ApiError as e:
        check("TIME (clock not set is allowed)", e.code == 503, e)
    st, data = api.cmd("HELP")
    check("HELP lists commands", len(data) > 5)
    expect_er("unknown command -> 400", 400, lambda: api.cmd("FROB"))

    # a fresh scratch folder
    try:
        for e in api.dir("/RPAPITST")[0]:
            api.cmd('DEL "/RPAPITST/%s"' % e[5])
        api.cmd("DEL /RPAPITST")
    except ApiError:
        pass
    api.cmd("MKDIR /RPAPITST")
    expect_er("MKDIR existing -> 409", 409, lambda: api.cmd("MKDIR /RPAPITST"))
    check("CD /RPAPITST", api.cmd("CD /RPAPITST")[0] == "/RPAPITST")
    check("CD shows the folder", api.cmd("CD")[0] == "/RPAPITST")
    check("CD .. goes up", api.cmd("CD ..")[0] == "/")
    api.cmd("CD RPAPITST")
    expect_er("CD to a missing folder -> 404", 404, lambda: api.cmd("CD NOPE"))

    blob = bytes(random.getrandbits(8) for _ in range(5000)) + bytes(range(256)) * 4
    for hexmode in (False, True):
        api.mode(hexmode)
        name = "T%s.BIN" % ("HEX" if hexmode else "BIN")
        h, size = api.open(name, "W")
        check("OPEN W gives size 0 (%s)" % name, size == 0)
        off = 0
        for n in (1, 127, 128, 1000, api.block, 7):
            api.write(h, off, blob[off:off + n])
            off += n
        while off < len(blob):
            api.write(h, off, blob[off:off + api.block])
            off += api.block
        api.close(h)
        check("STAT size after WRITE (%s)" % name, api.stat(name)[1] == len(blob))
        h, size = api.open(name, "R")
        back, off = b"", 0
        for n in (1, 300, api.block):
            back += api.read(h, off, n)
            off += n
        while True:
            d = api.read(h, off, api.block)
            if not d:
                break
            back += d
            off += len(d)
        check("READ back matches (%s)" % name, back == blob)
        check("READ past the end is empty", api.read(h, len(blob) + 10, 10) == b"")
        expect_er("WRITE on a read handle -> 405", 405, lambda: api.cmd("WRITE %d 0 1 -" % h))
        api.close(h)
    api.mode(False)

    # errors that must keep the session in step
    h, _ = api.open("TERR.BIN", "W")
    expect_er("WRITE over BLOCK -> 413", 413, lambda: api.cmd("WRITE %d 0 %d -" % (h, api.block + 1)))
    expect_er("WRITE past the end -> 400", 400, lambda: api.cmd("WRITE %d 5 1 -" % h))
    expect_er("READ over BLOCK -> 413", 413, lambda: api.cmd("READ %d 0 %d" % (h, api.block + 1)))
    st, _ = api.cmd("WRITE %d 0 4 0000" % h)          # wrong CRC on purpose
    api.link.write(b"ABCD")
    expect_er("WRITE with a bad CRC -> 412", 412, api.cmd_status)
    st, _ = api.cmd("WRITE %d 0 4 -" % h)             # no CRC check
    api.link.write(b"ABCD")
    check("WRITE without a CRC", int(api.cmd_status()[0]) == 4)
    expect_er("bad handle -> 405", 405, lambda: api.cmd("READ 9 0 1"))
    if slow:
        st, _ = api.cmd("WRITE %d 0 10 -" % h)
        api.link.write(b"12345")
        expect_er("WRITE data stops -> 504 (10 s)", 504, lambda: api.cmd_status(timeout=20))
    api.close(h)
    h, size = api.open("TERR.BIN", "A")
    check("OPEN A keeps the contents", size == 4)
    api.write(h, 4, b"EF")
    api.close(h)
    h, _ = api.open("TERR.BIN", "R")
    check("append, then read", api.read(h, 0, 100) == b"ABCDEF")
    api.close(h)
    hs = [api.open("TERR.BIN", "R")[0] for _ in range(4)]
    expect_er("fifth handle -> 409", 409, lambda: api.open("TERR.BIN", "R"))
    api.close()
    check("CLOSE with no handle closes all", api.open("TERR.BIN", "R")[0] == 1)
    api.close()

    # names, listing, rename, delete
    h, _ = api.open("A long name.txt", "W")
    api.write(h, 0, b"hello\r\n")
    api.close(h)
    e = api.stat("A long name.txt")
    check("long name with spaces", e[5] == "A long name.txt" and e[1] == 7, e)
    check("STAT gives an 8.3 alias or -", e[4] == "-" or len(e[4]) <= 12, e)
    if e[4] == "-":
        print("  (no 8.3 alias: exFAT card or a retro-ports server)")
    else:
      try:
        h, _ = api.open(e[4], "R")
        check("open by the 8.3 alias", api.read(h, 0, 10) == b"hello\r\n")
        api.close(h)
      except ApiError as x:
        check("open by the 8.3 alias", False, x)
    names = {x[5] for x in api.dir()[0]}
    check("DIR lists the files", {"TBIN.BIN", "THEX.BIN", "TERR.BIN", "A long name.txt"} <= names, names)
    ents, more = api.dir("*.BIN")
    check("DIR pattern *.BIN", sorted(x[5] for x in ents) == ["TBIN.BIN", "TERR.BIN", "THEX.BIN"], ents)
    ents, more = api.dir("/RPAPITST", 1, 2)
    check("DIR start/count pages with MORE", len(ents) == 2 and more, (ents, more))
    ents, more = api.dir("/RPAPITST", 3, 5)
    check("DIR last page without MORE", len(ents) == 1 and not more, (ents, more))
    api.cmd("MKDIR SUB")
    api.cmd('REN "A long name.txt" SUB/MOVED.TXT')
    check("REN moves into a folder", api.stat("/RPAPITST/SUB/MOVED.TXT")[1] == 7)
    expect_er("STAT of a moved file -> 404", 404, lambda: api.stat("A long name.txt"))
    expect_er("DEL of a non-empty folder -> 409", 409, lambda: api.cmd("DEL SUB"))
    api.cmd("DEL SUB\\MOVED.TXT")
    api.cmd("DEL SUB")
    check("DIR of one file", api.dir("TBIN.BIN")[0][0][5] == "TBIN.BIN")
    st, _ = api.cmd("FREE", timeout=600)
    tot, fr = map(int, st.split())
    check("FREE gives total and free KB", tot > 0 and 0 <= fr <= tot, st)

    # XMODEM both ways
    small = bytes(random.getrandbits(8) for _ in range(1000))
    st, _ = api.cmd("XPUT XM.BIN")
    check("XPUT says GO", st == "GO")
    xmodem_send(api, small)
    st, _ = api.cmd_status(60)
    check("XPUT stores the file (padded to 128)", int(st) == 1024, st)
    st, _ = api.cmd("XGET XM.BIN")
    got = xmodem_receive(api)
    api.cmd_status(60)
    check("XGET sends it back", got[:1000] == small)
    expect_er("XGET of a missing file -> 404", 404, lambda: api.cmd("XGET NOPE.BIN"))

    if not offline:
        st, data = api.cmd("FETCH http://n9taxretrolab.net/ PAGE.HTM", timeout=120)
        size = int(st.split()[0])
        check("FETCH saves a web page", size > 200 and api.stat("PAGE.HTM")[1] == size, st)
        expect_er("FETCH of a bad host -> 502", 502, lambda: api.cmd("FETCH http://nonexistent.invalid/x", timeout=120))
        expect_er("FETCH of a missing page -> 502", 502,
                  lambda: api.cmd("FETCH http://n9taxretrolab.net/no-such-page", timeout=120))

    for e in api.dir()[0]:
        api.cmd('DEL "%s"' % e[5])
    api.cmd("CD /")
    api.cmd("DEL RPAPITST")
    expect_er("scratch folder removed", 404, lambda: api.stat("/RPAPITST"))
    print("\n%s" % ("ALL PASSED" if not fails else "%d FAILED: %s" % (len(fails), ", ".join(fails))))
    return not fails


# ---------------------------------------------------------------- command line

def main():
    ap = argparse.ArgumentParser(description="RPAPI 1 client for RETRO-PORT", epilog=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    g = ap.add_mutually_exclusive_group(required=True)
    g.add_argument("--serial", metavar="DEV")
    g.add_argument("--tcp", metavar="HOST:PORT", help="a retro-ports raw port")
    ap.add_argument("--baud", type=int, default=9600)
    ap.add_argument("--hex", action="store_true", help="MODE HEX (7-bit lines)")
    ap.add_argument("--block", type=int, help="bytes per READ/WRITE (default: BLOCK)")
    ap.add_argument("--offline", action="store_true", help="test: skip FETCH")
    ap.add_argument("--slow", action="store_true", help="test: include the 10 s timeout case")
    ap.add_argument("-v", "--verbose", action="store_true", help="show every line")
    ap.add_argument("command")
    ap.add_argument("args", nargs="*")
    a = ap.parse_args()
    link = SerialLink(a.serial, a.baud) if a.serial else TcpLink(a.tcp)
    api = RPAPI(link, a.verbose)
    print(api.wake(), file=sys.stderr)
    if a.hex:
        api.mode(True)

    def bar(done, total):
        print("\r%d of %d bytes" % (done, total), end="", file=sys.stderr, flush=True)

    c, args, ok = a.command.lower(), a.args, True
    try:
        if c == "dir":
            ents, more = api.dir(args[0] if args else "")
            for t, size, date, tm, short, name in ents:
                print("%-5s %10s  %s %s  %-12s %s" % ("<DIR>" if t == "D" else "", size if t == "F" else "",
                                                       date, tm, short, name))
            if more:
                print("(more)")
        elif c == "get":
            local = args[1] if len(args) > 1 else os.path.basename(args[0].replace("\\", "/"))
            n = api.get(args[0], local, a.block, bar)
            print("\n%d bytes to %s" % (n, local), file=sys.stderr)
        elif c == "put":
            remote = args[1] if len(args) > 1 else os.path.basename(args[0])
            n = api.put(args[0], remote, a.block, bar)
            print("\n%d bytes to %s" % (n, remote), file=sys.stderr)
        elif c == "xget":
            api.cmd('XGET "%s" 1K' % args[0])
            d = xmodem_receive(api)
            api.cmd_status(60)
            local = args[1] if len(args) > 1 else os.path.basename(args[0])
            open(local, "wb").write(d)
        elif c == "xput":
            api.cmd('XPUT "%s"' % (args[1] if len(args) > 1 else os.path.basename(args[0])))
            xmodem_send(api, open(args[0], "rb").read())
            print(api.cmd_status(60)[0])
        elif c == "fetch":
            st, _ = api.cmd(" ".join(['FETCH "%s"' % args[0]] + ['"%s"' % x for x in args[1:]]), timeout=120,
                            progress=lambda p: print("\r" + p + " bytes", end="", file=sys.stderr, flush=True))
            print("\n" + st)
        elif c in ("del", "mkdir", "ren", "stat", "free", "time", "status", "cd"):
            st, data = api.cmd(" ".join([c.upper()] + ['"%s"' % x for x in args]), timeout=600)
            for d in data:
                print(d)
            if st:
                print(st)
        elif c == "shell":
            print("Type commands (BYE or Ctrl-D ends). READ/WRITE data isn't shown.", file=sys.stderr)
            for ln in sys.stdin:
                try:
                    st, data = api.cmd(ln.strip(), timeout=600, progress=print)
                    print("OK " + st if st and not st.startswith(("GO", "DATA")) else st or "OK")
                except ApiError as e:
                    print(e)
                if ln.strip().upper() == "BYE":
                    return
        elif c == "test":
            ok = run_test(api, a.offline, a.slow)
        else:
            ap.error("unknown command " + c)
    except ApiError as e:
        print(e, file=sys.stderr)
        ok = False
    finally:
        try:
            if c != "shell":
                api.cmd("BYE", timeout=5)
        except Exception:
            pass
        link.close()
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
