#!/bin/bash

# 微服务配置更新脚本
# 为所有微服务添加bootstrap.yml和更新application.yml

SERVICES_DIR="services"

# 服务列表
services=(
  "user-service"
  "product-service" 
  "order-service"
  "inventory-service"
  "finance-service"
  "admin-service"
  "file-service"
  "notification-service"
  "tenant-service"
)

# 公共bootstrap.yml模板
BOOTSTRAP_TEMPLATE='spring:
  application:
    name: ${SERVICE_NAME}
  
  cloud:
    nacos:
      config:
        server-addr: ${NACOS_SERVER_ADDR:localhost:8848}
        namespace: ${NACOS_NAMESPACE:public}
        group: ${NACOS_GROUP:DEFAULT_GROUP}
        file-extension: yaml
        shared-configs:
          - data-id: common-config.yaml
            group: DEFAULT_GROUP
            refresh: true
          - data-id: datasource-config.yaml
            group: DEFAULT_GROUP
            refresh: true
          - data-id: redis-config.yaml
            group: DEFAULT_GROUP
            refresh: true
        extension-configs:
          - data-id: ${SERVICE_NAME}-config.yaml
            group: DEFAULT_GROUP
            refresh: true
      
      discovery:
        server-addr: ${NACOS_SERVER_ADDR:localhost:8848}
        namespace: ${NACOS_NAMESPACE:public}
        group: ${NACOS_GROUP:DEFAULT_GROUP}
        metadata:
          version: 1.0.0
          zone: ${ZONE:zone1}
        
  config:
    import:
      - optional:nacos:common-config.yaml
      - optional:nacos:datasource-config.yaml
      - optional:nacos:redis-config.yaml
      - optional:nacos:${SERVICE_NAME}-config.yaml

# 激活配置文件
profiles:
  active: ${PROFILE:dev}'

echo "开始更新微服务配置..."

for service in "${services[@]}"; do
  service_dir="$SERVICES_DIR/$service"
  
  if [ -d "$service_dir" ]; then
    echo "更新服务: $service"
    
    # 创建bootstrap.yml
    echo "$BOOTSTRAP_TEMPLATE" | sed "s/\${SERVICE_NAME}/$service/g" > "$service_dir/src/main/resources/bootstrap.yml"
    
    # 更新application.yml - 移除Nacos配置
    if [ -f "$service_dir/src/main/resources/application.yml" ]; then
      # 备份原文件
      cp "$service_dir/src/main/resources/application.yml" "$service_dir/src/main/resources/application.yml.backup"
      
      # 移除Nacos配置部分（简单处理，实际可能需要更复杂的处理）
      grep -v "nacos:" "$service_dir/src/main/resources/application.yml" | \
        grep -v "server-addr:" | \
        grep -v "namespace:" | \
        grep -v "file-extension:" > "$service_dir/src/main/resources/application.yml.tmp"
      
      mv "$service_dir/src/main/resources/application.yml.tmp" "$service_dir/src/main/resources/application.yml"
      
      echo "  - 已更新application.yml"
    fi
    
    echo "  - 已创建bootstrap.yml"
  else
    echo "警告: 服务目录不存在: $service_dir"
  fi
done

echo "微服务配置更新完成！"
echo ""
echo "下一步:"
echo "1. 启动Nacos服务: docker-compose -f nacos/docker-compose.yml up -d"
echo "2. 在Nacos控制台创建配置:"
echo "   - common-config.yaml"
echo "   - datasource-config.yaml" 
echo "   - redis-config.yaml"
echo "   - 各服务的xxx-service-config.yaml"
echo "3. 启动各微服务"