#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  cloud-smoke-test.sh --host <hostname-or-ip> [options]

Options:
  --host <value>            Required. Tailnet hostname or IP.
  --uci-port <value>        UCI port. Default: 5555
  --mgmt-port <value>       Management port. Default: 53350
  --auth-token <value>      Optional UCI auth token.
  --expect-engine <value>   Optional engine name expected in scan output.
  --timeout <seconds>       netcat timeout. Default: 5
  --help                    Show this help.
EOF
}

require_cmd() {
  command -v "$1" >/dev/null 2>&1 || {
    echo "ERROR: required command not found: $1" >&2
    exit 1
  }
}

HOST=""
UCI_PORT="5555"
MGMT_PORT="53350"
AUTH_TOKEN=""
EXPECT_ENGINE=""
TIMEOUT="5"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --host)
      HOST="${2:-}"
      shift 2
      ;;
    --uci-port)
      UCI_PORT="${2:-}"
      shift 2
      ;;
    --mgmt-port)
      MGMT_PORT="${2:-}"
      shift 2
      ;;
    --auth-token)
      AUTH_TOKEN="${2:-}"
      shift 2
      ;;
    --expect-engine)
      EXPECT_ENGINE="${2:-}"
      shift 2
      ;;
    --timeout)
      TIMEOUT="${2:-}"
      shift 2
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "ERROR: unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

if [[ -z "${HOST}" ]]; then
  echo "ERROR: --host is required." >&2
  usage
  exit 1
fi

require_cmd nc
require_cmd grep

echo "[1/3] scan check -> ${HOST}:${MGMT_PORT}"
SCAN_OUT="$(printf 'scan' | nc -w "${TIMEOUT}" "${HOST}" "${MGMT_PORT}" || true)"
echo "${SCAN_OUT}"
echo "${SCAN_OUT}" | grep -q "scanisdone" || {
  echo "ERROR: scan output missing 'scanisdone'." >&2
  exit 1
}
if [[ -n "${EXPECT_ENGINE}" ]]; then
  echo "${SCAN_OUT}" | grep -q "_${EXPECT_ENGINE}" || {
    echo "ERROR: scan output missing expected engine '${EXPECT_ENGINE}'." >&2
    exit 1
  }
fi

echo "[2/3] query check -> ${HOST}:${MGMT_PORT}"
QUERY_OUT="$(printf 'query' | nc -w "${TIMEOUT}" "${HOST}" "${MGMT_PORT}" || true)"
echo "${QUERY_OUT}"
echo "${QUERY_OUT}" | grep -q "querydone" || {
  echo "ERROR: query output missing 'querydone'." >&2
  exit 1
}

echo "[3/3] uci check -> ${HOST}:${UCI_PORT}"
if [[ -n "${AUTH_TOKEN}" ]]; then
  UCI_OUT="$(
    {
      echo "AUTH ${AUTH_TOKEN}"
      echo "uci"
      echo "isready"
      echo "quit"
    } | nc -w "${TIMEOUT}" "${HOST}" "${UCI_PORT}" || true
  )"
else
  UCI_OUT="$(
    {
      echo "uci"
      echo "isready"
      echo "quit"
    } | nc -w "${TIMEOUT}" "${HOST}" "${UCI_PORT}" || true
  )"
fi
echo "${UCI_OUT}"
echo "${UCI_OUT}" | grep -q "uciok" || {
  echo "ERROR: UCI output missing 'uciok'." >&2
  exit 1
}
echo "${UCI_OUT}" | grep -q "readyok" || {
  echo "ERROR: UCI output missing 'readyok'." >&2
  exit 1
}

echo "PASS: cloud bridge scan/query/UCI checks succeeded."
