#!/bin/bash
set -euo pipefail

have_cmd() { command -v "$1" >/dev/null 2>&1; }

# Always run from the directory this script lives in
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

TCP_CMD=""

# Preferred: local build in ./tcpser/
if [[ -x "tcpser/tcpser" ]]; then
  TCP_CMD="./tcpser/tcpser"

# Fallback: tcpser installed in PATH (e.g. /usr/local/bin)
elif have_cmd tcpser; then
  TCP_CMD="tcpser"
fi

if [[ -z "$TCP_CMD" ]]; then
  echo "ERROR: tcpser not found."
  echo "Expected one of:"
  echo " - ./tcpser/tcpser (local build)"
  echo " - tcpser in PATH (e.g. /usr/local/bin/tcpser)"
  echo "Have you built tcpser yet?"
  exit 1
fi

echo "Using tcpser: $TCP_CMD"

# ---- Launch tcpser ----
"$TCP_CMD" \
  -p 8502 \
  -l 4 \
  -v 25237 \
  -s 38400 \
  -A answer.txt \
  -C connect.txt \
  -N noanswer.txt \
  -B busy.txt
