#!/bin/bash
# deploy_test_nodes.sh: Spawns N test agent nodes on the production host for mesh testing.
# Usage: ./deploy_test_nodes.sh [COUNT] (default 2)

COUNT=${1:-2}
HOST="${REMOTE_HOST:-192.168.68.113}"
USER="${REMOTE_USER:-axieyangb}"
PASS="${REMOTE_PASS}"

# Load credentials from GitBucket if not in environment
if [ -z "$PASS" ]; then
    if [ -f "/app/.env.gitbucket" ]; then source "/app/.env.gitbucket"; fi
    GITBUCKET_TOKEN="${GITBUCKET_TOKEN}"
    SNIPPET_ID="${DEPLOYMENT_SNIPPET_ID}"
    if [ -n "$GITBUCKET_TOKEN" ] && [ -n "$SNIPPET_ID" ]; then
        TMP_SECRETS=$(mktemp -d)
        if git clone "https://yangyangxie:${GITBUCKET_TOKEN}@gitbucket.jerxie.com/git/gist/yangyangxie/${SNIPPET_ID}.git" "$TMP_SECRETS" &> /dev/null; then
            source "$TMP_SECRETS/.env.production"
            PASS="${REMOTE_PASSWORD:-$PASS}"
        fi
        rm -rf "$TMP_SECRETS"
    fi
fi

if [ -z "$PASS" ]; then echo "Error: REMOTE_PASS not found."; exit 1; fi

REMOTE_PROJ="/home/coder/project/cortex-hub"
AGENT_DIR="$REMOTE_PROJ/agent-node"

echo "🚀 Deploying $COUNT test nodes to $HOST..."

# We use docker run instead of compose to allow scaling with unique names/IDs easily
# without modifying the persistent docker-compose.yml on the server.

sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$USER@$HOST" << EOF
  # 1. Ensure the base image is built
  cd $AGENT_DIR
  echo '$PASS' | sudo -S docker build -t agent-node-base .

  # 2. Cleanup any previous test nodes
  echo "Cleaning up old test nodes..."
  echo '$PASS' | sudo -S docker ps -a --filter "name=cortex-test-node-" -q | xargs -r -I % sh -c "echo '$PASS' | sudo -S docker rm -f %"

  # 3. Spawn N nodes
  for i in \$(seq 1 $COUNT); do
    NODE_ID="test-node-\$i"
    CONTAINER_NAME="cortex-test-node-\$i"
    
    echo "[+] Starting \$CONTAINER_NAME..."
    
    # Determine the correct token based on node number (matches docker-compose.test-nodes.yml)
    if [ "\$i" -eq 1 ]; then
      NODE_TOKEN="cortex-secret-shared-key"
    else
      NODE_TOKEN="ysHjZIRXeWo-YYK6EWtBsIgJ4uNBihSnZMtt0BQW3eI"
    fi

    echo '$PASS' | sudo -S docker run -d \\
      --name "\$CONTAINER_NAME" \\
      --network cortex-hub_default \\
      -e AGENT_NODE_ID="\$NODE_ID" \\
      -e AGENT_NODE_DESC="Scalable Test Node #\$i" \\
      -e GRPC_ENDPOINT="ai_hub_service:50051" \\
      -e AGENT_HUB_URL="http://ai_hub_service:8000" \\
      -e AGENT_AUTH_TOKEN="\$NODE_TOKEN" \\
      -e AGENT_SECRET_KEY="aYc2j1lYUUZXkBFFUndnleZI" \\
      -e AGENT_TLS_ENABLED="false" \\
      agent-node-base
  done

  echo "✅ Spawning complete. Currently running test nodes:"
  echo '$PASS' | sudo -S docker ps --filter "name=cortex-test-node-"
EOF

echo "✨ Done! Check https://ai.jerxie.com/nodes to see the new nodes join the mesh."
