#!/usr/bin/env bash
# RSSH control-plane smoke: whitelist → open session → connect payload with bastion fields.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=ra_lib.sh
source "$ROOT/scripts/ra_lib.sh"

BASE="$(ra_base)"
DEVICE_ID="${RA_DEVICE_ID:-rssh-smoke-$(date +%s)}"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

ra_admin_login "$COOKIE_JAR"

body=$(printf '{"heartbeat":{"type":"ra","status":"enable","device_id":"%s","random":"r0","tunnel_mode":"rssh","capabilities":["rssh","shell"]}}' "$DEVICE_ID")
code=$(curl -sS -o /tmp/rssh-hb.json -w '%{http_code}' -X POST -H 'Content-Type: application/json' -d "$body" "$(ra_heartbeat_url)")
[[ "$code" == "200" ]] || { echo "FAIL heartbeat enable HTTP $code"; cat /tmp/rssh-hb.json; exit 1; }
grep -q '"action":"wait"' /tmp/rssh-hb.json && echo OK wait

ra_admin_post "$COOKIE_JAR" whitelist "$(printf '{"device_id":"%s","whitelisted":true}' "$DEVICE_ID")" >/dev/null
ra_admin_post "$COOKIE_JAR" open_session "$(printf '{"device_id":"%s"}' "$DEVICE_ID")" >/dev/null

body=$(printf '{"heartbeat":{"type":"ra","status":"enable","device_id":"%s","random":"r1","tunnel_mode":"rssh","capabilities":["rssh","shell"]}}' "$DEVICE_ID")
curl -sf -X POST -H 'Content-Type: application/json' -d "$body" "$(ra_heartbeat_url)" > /tmp/rssh-connect.json
grep -q '"action":"connect"' /tmp/rssh-connect.json && echo OK connect
grep -q 'bastion_host' /tmp/rssh-connect.json && echo OK bastion fields
grep -q 'remote_port' /tmp/rssh-connect.json && echo OK remote_port

echo "All RSSH API checks passed."
