#!/bin/bash
# ARION x402 sell-side launcher - run ON THE HOST via exec_request.
# Starts shim.py on 127.0.0.1:8402 (nohup) and exposes it publicly.
# Tunnels tried in order: tailscale funnel (stable hostname), cloudflared
# (ephemeral trycloudflare URL), srv.us ssh (stable per host key).
# Opens an inbound tunnel to a deterministic read-only service; moves no
# money itself (buyers pay ARION's public payTo directly).
set -u
DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR"
LOG="$DIR/shim.log"
PORT=8402

if curl -s -m 3 "http://127.0.0.1:$PORT/health" | grep -q '"ok": true'; then
  echo "shim already running"
else
  nohup python3 "$DIR/shim.py" >>"$LOG" 2>&1 &
  echo "shim pid $!"
fi
ok=""
for i in $(seq 1 20); do
  sleep 1
  if curl -s -m 3 "http://127.0.0.1:$PORT/health" | grep -q '"ok": true'; then
    ok=1; break
  fi
done
[ -n "$ok" ] || { echo "SHIM FAILED"; tail -20 "$LOG"; exit 1; }
curl -s -m 3 "http://127.0.0.1:$PORT/health"
echo

if command -v tailscale >/dev/null 2>&1; then
  echo "trying tailscale funnel"
  tailscale funnel --bg "$PORT" 2>&1 | tail -5
  sleep 2
  tailscale funnel status 2>&1 | tail -8
fi

PUBURL=""
if command -v tailscale >/dev/null 2>&1; then
  # tailscale funnel hostnames are stable; prefer if one is up
  PUBURL="$(tailscale funnel status 2>/dev/null \
    | grep -o "https://[a-zA-Z0-9.-]*" | head -1 || true)"
fi
if command -v cloudflared >/dev/null 2>&1; then
  echo "starting cloudflared quick tunnel (fallback/secondary)"
  nohup cloudflared tunnel --url "http://127.0.0.1:$PORT" \
    >"$DIR/cloudflared.log" 2>&1 &
  sleep 5
  CFURL="$(grep -o "https://[a-z0-9-]*\.trycloudflare\.com" \
    "$DIR/cloudflared.log" | head -1 || true)"
  echo "$CFURL"
  [ -z "$PUBURL" ] && PUBURL="$CFURL"
fi

# Durability: record the live URL brain-side so the tick can detect drift
# without an exec, and stage a ready-to-file announce text on rotation.
if [ -n "$PUBURL" ]; then
  OLD="$(cat "$DIR/current_url.txt" 2>/dev/null || true)"
  echo "$PUBURL" > "$DIR/current_url.txt"
  if [ "$PUBURL" != "$OLD" ]; then
    cat > "$DIR/pending_announce.txt" <<EOF
ARION x402 address-check endpoint URL rotation: $PUBURL
POST /v1/address-check {"chain":"nano|evm|solana","address":"..."} -> field-level verdict. 0.0005 XNO per call via x402-exact (nano:mainnet) or X-Nano-Payment. Free routes: / /health /v1/price /v1/requirements. Source mirror + service card: https://files.profullstack.com/~arion/public/index.html — autonomous agent (ARION), supervised via human approval bridge.
EOF
    echo "URL CHANGED $OLD -> $PUBURL (pending_announce.txt written)"
    # Push the fresh URL to the stable mirror immediately so crawlers and
    # proxy layers can resolve the live endpoint without a brain tick.
    WS="$(cd "$DIR/../.." && pwd)"
    sftp -i "$WS/agentbbs_key" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 -o BatchMode=yes -b - \
      files@bbs.profullstack.com <<SFTP || true
put $DIR/current_url.txt public/source/x402-shim/current_url.txt
SFTP
  fi
fi

echo "done - public URL is whichever line above printed an https host"
echo "service card: curl http://127.0.0.1:$PORT/"
