#!/bin/bash

# 为所有 Nomad Server 部署 Consul Client

echo "🚀 部署 Consul Client 到所有 Nomad Server 节点"
echo "================================================"

# 部署 Consul Client
echo "1. 部署 Consul Client..."
ansible-playbook -i ansible/inventory/hosts.yml \
  ansible/consul-client-deployment.yml \
  --limit nomad_servers

if [ $? -eq 0 ]; then
  echo "✅ Consul Client 部署成功"
else
  echo "❌ Consul Client 部署失败"
  exit 1
fi

# 更新 Nomad 配置
echo ""
echo "2. 更新 Nomad Server 配置..."
echo "需要手动更新每个 Nomad Server 的配置："
echo ""
echo "修改 /etc/nomad.d/nomad.hcl 中的 consul 块："
echo "consul {"
echo "  address = \"127.0.0.1:8500\"  # 改为本地"
echo "  server_service_name = \"nomad\""
echo "  client_service_name = \"nomad-client\""
echo "  auto_advertise = true"
echo "  server_auto_join = true"
echo "  client_auto_join = false"
echo "}"
echo ""
echo "然后重启 Nomad 服务："
echo "systemctl restart nomad"

echo ""
echo "3. 验证部署..."
sleep 5

# 验证 Consul Client
for server in semaphore ch3 ash1d ash2e ch2 de onecloud1; do
  echo "检查 $server..."
  if curl -s http://$server.tailnet-68f9.ts.net:8500/v1/status/leader > /dev/null 2>&1; then
    echo "✅ $server - Consul Client 运行正常"
  else
    echo "❌ $server - Consul Client 无响应"
  fi
done

echo ""
echo "🎉 部署完成！"
echo "下一步："
echo "1. 手动更新每个 Nomad Server 的配置文件"
echo "2. 重启 Nomad 服务"
echo "3. 验证 Nomad 与 Consul 的集成"
