#!/bin/bash

# Cloudpods 开发环境启动脚本
# 用于日常开发，不重置数据库，只启动服务

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Cloudpods 开发环境启动脚本${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# 加载环境变量
if [ -f "../.env.local" ]; then
    echo -e "${BLUE}加载 .env.local 配置...${NC}"
    set -a
    source ../.env.local
    set +a
fi

# 设置默认值
DB_HOST=${DB_HOST:-127.0.0.1}
DB_PORT=${DB_PORT:-3306}
DB_USER=${DB_USER:-root}
DB_PASSWORD=${DB_PASSWORD:-}
DB_NAME=${DB_NAME:-yunioncloud}

KEYSTONE_PORT=${KEYSTONE_PORT:-30500}
ADMIN_USER=${ADMIN_USER:-sysadmin}
ADMIN_PASSWORD=${ADMIN_PASSWORD:-admin@123}
ADMIN_PROJECT=${ADMIN_PROJECT:-system}
ADMIN_DOMAIN=${ADMIN_DOMAIN:-Default}
REGION_NAME=${REGION_NAME:-region0}

REGION_PORT=${REGION_PORT:-30889}
GLANCE_PORT=${GLANCE_PORT:-9292}
YUNIONCONF_PORT=${YUNIONCONF_PORT:-30888}
SCHEDULEDTASK_PORT=${SCHEDULEDTASK_PORT:-30950}
APIGATEWAY_PORT=${APIGATEWAY_PORT:-3000}

# 构建数据库连接字符串
if [ -z "$DB_PASSWORD" ]; then
    SQL_CONNECTION="mysql+pymysql://${DB_USER}@${DB_HOST}:${DB_PORT}/${DB_NAME}?charset=utf8mb4"
else
    SQL_CONNECTION="mysql+pymysql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}?charset=utf8mb4"
fi

# 通用服务启动参数
COMMON_ARGS="--auth-url http://127.0.0.1:${KEYSTONE_PORT}/v3 --admin-user ${ADMIN_USER} --admin-password ${ADMIN_PASSWORD} --admin-project ${ADMIN_PROJECT} --admin-domain ${ADMIN_DOMAIN}"

# 创建日志目录
mkdir -p logs

# 检查并编译服务
check_binary() {
    local service=$1
    if [ ! -f "_output/bin/${service}" ]; then
        echo -e "${YELLOW}编译 ${service}...${NC}"
        GOOS=darwin CGO_ENABLED=0 go build -mod vendor -o "_output/bin/${service}" "yunion.io/x/onecloud/cmd/${service}"
    fi
}

# 停止已运行的服务
stop_existing() {
    echo -e "${YELLOW}检查并停止已运行的服务...${NC}"
    for service in apigateway scheduledtask yunionconf glance region keystone; do
        if [ -f "logs/${service}.pid" ]; then
            pid=$(cat logs/${service}.pid)
            if ps -p $pid > /dev/null 2>&1; then
                echo "  停止 ${service} (PID: ${pid})"
                kill $pid 2>/dev/null || true
            fi
            rm -f logs/${service}.pid
        fi
    done
    sleep 1
}

# 启动服务
start_service() {
    local service=$1
    local port=$2
    local extra_args=$3
    
    echo -e "${YELLOW}启动 ${service} (端口 ${port})...${NC}"
    
    local port_args=""
    if [ "${service}" = "keystone" ]; then
        port_args="--port ${KEYSTONE_PORT} --admin-port 35357 --bootstrap-admin-user-password ${ADMIN_PASSWORD}"
    else
        port_args="--port ${port}"
    fi
    
    local sql_args=""
    if [ "${service}" != "apigateway" ]; then
        sql_args="--sql-connection \"${SQL_CONNECTION}\" --auto-sync-table"
    fi
    
    eval "_output/bin/${service} \
        --config /dev/null \
        ${sql_args} \
        ${port_args} \
        ${extra_args} \
        > logs/${service}.log 2>&1 &"
    
    echo $! > logs/${service}.pid
    echo -e "${GREEN}  ✓ ${service} 已启动 (PID: $!)${NC}"
}

# 等待服务就绪
wait_for_service() {
    local service=$1
    local url=$2
    local max_wait=${3:-30}
    
    echo -e "${YELLOW}等待 ${service} 就绪...${NC}"
    for i in $(seq 1 $max_wait); do
        if curl -s "$url" > /dev/null 2>&1; then
            echo -e "${GREEN}  ✓ ${service} 已就绪${NC}"
            return 0
        fi
        sleep 1
    done
    echo -e "${RED}  ✗ ${service} 启动超时${NC}"
    return 1
}

# 主流程
main() {
    # 停止已运行的服务
    stop_existing
    
    # 检查并编译所有服务
    echo -e "${BLUE}检查服务二进制文件...${NC}"
    check_binary keystone
    check_binary region
    check_binary glance
    check_binary yunionconf
    check_binary scheduledtask
    check_binary apigateway
    
    # 启动 Keystone
    start_service keystone ${KEYSTONE_PORT} ""
    wait_for_service "Keystone" "http://127.0.0.1:${KEYSTONE_PORT}/v3" 30
    
    # 创建 glance 数据目录
    mkdir -p /tmp/glance_data
    
    # 启动其他服务
    start_service region ${REGION_PORT} "${COMMON_ARGS}"
    start_service glance ${GLANCE_PORT} "${COMMON_ARGS} --filesystem-store-datadir /tmp/glance_data"
    start_service yunionconf ${YUNIONCONF_PORT} "${COMMON_ARGS}"
    start_service scheduledtask ${SCHEDULEDTASK_PORT} "${COMMON_ARGS}"
    
    # APIGateway 特殊处理
    echo -e "${YELLOW}启动 APIGateway (端口 ${APIGATEWAY_PORT})...${NC}"
    _output/bin/apigateway \
        --config /dev/null \
        --port ${APIGATEWAY_PORT} \
        ${COMMON_ARGS} \
        --default-region ${REGION_NAME} \
        > logs/apigateway.log 2>&1 &
    echo $! > logs/apigateway.pid
    echo -e "${GREEN}  ✓ APIGateway 已启动 (PID: $!)${NC}"
    
    # 等待所有服务就绪
    echo ""
    echo -e "${YELLOW}等待所有服务就绪...${NC}"
    sleep 3
    
    # 打印状态
    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  服务启动完成！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo -e "${BLUE}服务状态:${NC}"
    for service in keystone region glance yunionconf scheduledtask apigateway; do
        if [ -f "logs/${service}.pid" ]; then
            pid=$(cat logs/${service}.pid)
            if ps -p $pid > /dev/null 2>&1; then
                echo -e "  ${GREEN}✓${NC} ${service} (PID: ${pid})"
            else
                echo -e "  ${RED}✗${NC} ${service} (已停止)"
            fi
        fi
    done
    echo ""
    echo -e "${BLUE}访问地址:${NC}"
    echo "  APIGateway: http://127.0.0.1:${APIGATEWAY_PORT}"
    echo "  Frontend:   http://localhost:8080"
    echo ""
    echo -e "${BLUE}常用命令:${NC}"
    echo "  查看日志: tail -f logs/*.log"
    echo "  停止服务: ./stop-backend.sh"
    echo ""
}

# 处理命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --help)
            echo "Cloudpods 开发环境启动脚本"
            echo ""
            echo "用法: $0 [选项]"
            echo ""
            echo "选项:"
            echo "  --help    显示帮助信息"
            echo ""
            echo "说明:"
            echo "  此脚本用于日常开发，不重置数据库，只启动服务。"
            echo "  如果是全新部署，请使用 init-cloudpods.sh"
            echo ""
            exit 0
            ;;
        *)
            echo "未知选项: $1"
            exit 1
            ;;
    esac
done

main