#!/usr/bin/env python3
# Send commands to the RIP harness control port on portable:1516
# Usage: hctl <cmd1> [,] <cmd2> [,] ...
# Multiple commands separated by ',' use a single connection.
# Exits as soon as any command returns ERROR:.
import socket, sys

args = sys.argv[1:]
if not args:
    print("Usage: hctl <command> [args...] [, <command> [args...]] ...", file=sys.stderr)
    sys.exit(1)

# Split args on ';' into separate commands
cmds = []
current = []
for a in args:
    if a == ',':
        if current:
            cmds.append(' '.join(current))
            current = []
    else:
        current.append(a)
if current:
    cmds.append(' '.join(current))

s = socket.create_connection(('portable', 1516), timeout=120)
buf = b''
# Read and discard the banner line
while b'\n' not in buf:
    buf += s.recv(4096)
buf = buf.split(b'\n', 1)[1]

exit_code = 0
for cmd in cmds:
    s.sendall((cmd + '\n').encode())
    while True:
        buf += s.recv(4096)
        lines = buf.split(b'\n')
        done = False
        for line in lines:
            text = line.decode('utf-8', errors='replace').rstrip('\r')
            if text == 'OK' or text.startswith('ERROR:'):
                for prev in lines:
                    prev_text = prev.decode('utf-8', errors='replace').rstrip('\r')
                    if prev_text:
                        print(prev_text)
                    if prev is line:
                        break
                # Keep remainder after this line for next command
                idx = buf.find(line) + len(line)
                while idx < len(buf) and buf[idx:idx+1] in (b'\r', b'\n'):
                    idx += 1
                buf = buf[idx:]
                done = True
                if text.startswith('ERROR:'):
                    exit_code = 1
                break
        if done:
            break

s.close()
sys.exit(exit_code)
