#!/bin/bash
# Sundynix 微服务启动脚本
# 用法: ./scripts/start.sh [服务名]
# 例如: ./scripts/start.sh system-rpc
#       ./scripts/start.sh all       (启动所有)
#       ./scripts/start.sh gateway

set -e

BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
APP_DIR="$BASE_DIR/app"

start_service() {
  local name="$1"
  local dir="$2"
  local entry="$3"
  local config="$4"

  echo "🚀 启动 $name ..."
  cd "$dir"
  go run "$entry" -f "$config" &
  echo "   PID: $!"
}

case "${1:-help}" in
  auth-api)
    start_service "auth-api" "$APP_DIR/auth/api" "auth.go" "etc/auth-api.yaml"
    ;;
  file-rpc)
    start_service "file-rpc" "$APP_DIR/file/rpc" "file.go" "etc/file.yaml"
    ;;
  file-api)
    start_service "file-api" "$APP_DIR/file/api" "file.go" "etc/file-api.yaml"
    ;;
  system-rpc)
    start_service "system-rpc" "$APP_DIR/system/rpc" "system.go" "etc/system.yaml"
    ;;
  system-api)
    start_service "system-api" "$APP_DIR/system/api" "system.go" "etc/system-api.yaml"
    ;;
  plant-rpc)
    start_service "plant-rpc" "$APP_DIR/plant/rpc" "plant.go" "etc/plant.yaml"
    ;;
  plant-api)
    start_service "plant-api" "$APP_DIR/plant/api" "plant.go" "etc/plant-api.yaml"
    ;;

  gateway)
    start_service "gateway" "$APP_DIR/gateway" "gateway.go" "etc/gateway.yaml"
    ;;
  all)
    echo "===== 启动 RPC 层 ====="
    start_service "file-rpc"   "$APP_DIR/file/rpc"   "file.go"   "etc/file.yaml"
    start_service "system-rpc" "$APP_DIR/system/rpc" "system.go" "etc/system.yaml"
    start_service "plant-rpc"  "$APP_DIR/plant/rpc"  "plant.go"  "etc/plant.yaml"

    sleep 3
    echo "===== 启动 API 层 ====="
    start_service "auth-api"   "$APP_DIR/auth/api"   "auth.go"   "etc/auth-api.yaml"
    start_service "file-api"   "$APP_DIR/file/api"   "file.go"   "etc/file-api.yaml"
    start_service "system-api" "$APP_DIR/system/api" "system.go" "etc/system-api.yaml"
    start_service "plant-api"  "$APP_DIR/plant/api"  "plant.go"  "etc/plant-api.yaml"

    sleep 2
    echo "===== 启动网关 ====="
    start_service "gateway"    "$APP_DIR/gateway"    "gateway.go" "etc/gateway.yaml"
    echo ""
    echo "✅ 全部启动完成，按 Ctrl+C 停止所有服务"
    wait
    ;;
  stop)
    echo "停止所有 sundynix 服务..."
    pkill -f "sundynix-micro-go/app" 2>/dev/null || true
    echo "✅ 已停止"
    ;;
  *)
    echo "用法: $0 {auth-api|file-rpc|file-api|system-rpc|system-api|plant-rpc|plant-api|gateway|all|stop}"
    ;;
esac
