#!/bin/bash

# 向所有三个 Consul 节点注册 Traefik 服务
# 解决 Consul leader 轮换问题

CONSUL_NODES=(
  "ch4.tailnet-68f9.ts.net:8500"
  "warden.tailnet-68f9.ts.net:8500"
  "ash3c.tailnet-68f9.ts.net:8500"
)

TRAEFIK_IP="100.97.62.111"
ALLOC_ID=$(nomad job allocs traefik-consul-lb | head -2 | tail -1 | awk '{print $1}')

SERVICE_DATA_LB="{
  \"ID\": \"traefik-consul-lb-${ALLOC_ID}\",
  \"Name\": \"consul-lb\",
  \"Tags\": [\"consul\", \"loadbalancer\", \"traefik\", \"multi-node\"],
  \"Address\": \"${TRAEFIK_IP}\",
  \"Port\": 80,
  \"Check\": {
    \"HTTP\": \"http://${TRAEFIK_IP}:80/\",
    \"Interval\": \"30s\",
    \"Timeout\": \"15s\"
  }
}"

SERVICE_DATA_DASHBOARD="{
  \"ID\": \"traefik-dashboard-${ALLOC_ID}\",
  \"Name\": \"traefik-dashboard\",
  \"Tags\": [\"traefik\", \"dashboard\", \"multi-node\"],
  \"Address\": \"${TRAEFIK_IP}\",
  \"Port\": 8080,
  \"Check\": {
    \"HTTP\": \"http://${TRAEFIK_IP}:8080/api/overview\",
    \"Interval\": \"30s\",
    \"Timeout\": \"15s\"
  }
}"

echo "Registering Traefik services to all Consul nodes..."
echo "Allocation ID: ${ALLOC_ID}"
echo "Traefik IP: ${TRAEFIK_IP}"

for node in "${CONSUL_NODES[@]}"; do
  echo "Registering to ${node}..."
  
  # 注册 consul-lb 服务
  curl -s -X PUT "http://${node}/v1/agent/service/register" \
    -H "Content-Type: application/json" \
    -d "${SERVICE_DATA_LB}"
  
  # 注册 traefik-dashboard 服务
  curl -s -X PUT "http://${node}/v1/agent/service/register" \
    -H "Content-Type: application/json" \
    -d "${SERVICE_DATA_DASHBOARD}"
  
  echo "✓ Registered to ${node}"
done

echo ""
echo "🎉 Services registered to all Consul nodes!"
echo ""
echo "Verification:"
for node in "${CONSUL_NODES[@]}"; do
  echo "Services on ${node}:"
  curl -s "http://${node}/v1/catalog/services" | jq -r 'keys[]' | grep -E "(consul-lb|traefik-dashboard)" | sed 's/^/  - /'
done
