source ../environment.sh

if [ -z "$NETWORK" ]; then
echo "错误: 未找到 NETWORK 环境变量"
exit 1
fi
if [ -z "$CONSUL_NAME" ]; then
echo "错误: 未找到 CONSUL_NAME 环境变量"
exit 1
fi
if [ -z "$CONSUL_IMAGE" ]; then
echo "错误: 未找到 CONSUL_IMAGE 环境变量"
exit 1
fi
if [ -z "$CONSUL_PORT" ]; then
echo "错误: 未找到 CONSUL_PORT 环境变量"
exit 1
fi
if [ -z "$CONSUL_MEMORY" ]; then
echo "错误: 未找到 CONSUL_MEMORY 环境变量"
exit 1
fi

# 停止并删除已存在的容器
if docker ps -a | grep -q ${CONSUL_NAME}; then
    echo "停止并删除已存在的 Consul 容器..."
    docker stop ${CONSUL_NAME} >/dev/null 2>&1
    docker rm ${CONSUL_NAME} >/dev/null 2>&1
fi


# 启动Consul容器
echo "启动 Consul..."
docker run -d \
    --name ${CONSUL_NAME} \
    --network $NETWORK \
    --memory $CONSUL_MEMORY \
    --restart unless-stopped \
    -p ${CONSUL_PORT}:8500 \
    --mount type=bind,source=/etc/localtime,target=/etc/localtime,readonly \
    $CONSUL_IMAGE agent -dev -client=0.0.0.0 -ui

# 等待Consul启动
echo "等待 Consul 就绪..."
until docker exec ${CONSUL_NAME} consul members 2>/dev/null; do
    echo "等待 Consul 启动..."
    sleep 3
done

echo "Consul 部署完成!"
echo "UI 访问地址: http://localhost:${CONSUL_PORT}"


# echo "Service $SERVICE_NAME . Creating..."
#     docker service create \
#        --name "$SERVICE_NAME" \
#        --env CONSUL_BIND_INTERFACE=eth0 \
#        --restart-condition any \
#        --network "$NETWORK" \
#        --publish published=8500,target=8500 \
#        --constraint 'node.role == manager' \
#        consul
# docker service ls
