#!/bin/bash

# 设置颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 打印带颜色的信息
print_info() {
    echo -e "${GREEN}[INFO] $1${NC}"
}

print_error() {
    echo -e "${RED}[ERROR] $1${NC}"
}

# 检查必要的命令
check_commands() {
    print_info "检查必要的命令..."
    commands=("docker" "docker-compose" "node" "npm")
    for cmd in "${commands[@]}"; do
        if ! command -v $cmd &> /dev/null; then
            print_error "$cmd 未安装"
            exit 1
        fi
    done
}

# 创建必要的目录
create_directories() {
    print_info "创建必要的目录..."
    mkdir -p nginx/conf.d nginx/ssl frontend/dist
}

# 构建前端
build_frontend() {
    print_info "构建前端..."
    cd frontend
    npm install
    npm run build
    cd ..
}

# 检查环境变量
check_env() {
    print_info "检查环境变量..."
    if [ ! -f .env ]; then
        print_error "未找到 .env 文件"
        exit 1
    fi
}

# 检查SSL证书
check_ssl() {
    print_info "检查SSL证书..."
    if [ ! -f nginx/ssl/cert.pem ] || [ ! -f nginx/ssl/key.pem ]; then
        print_info "未找到SSL证书，将使用HTTP模式"
        # 修改nginx配置，移除SSL相关配置
        sed -i '/ssl/d' nginx/conf.d/default.conf
        sed -i 's/443/80/g' nginx/conf.d/default.conf
    fi
}

# 启动服务
start_services() {
    print_info "启动服务..."
    docker-compose up -d
}

# 检查服务状态
check_services() {
    print_info "检查服务状态..."
    sleep 5
    if docker-compose ps | grep -q "Up"; then
        print_info "服务启动成功！"
        print_info "前端访问地址: http://localhost"
        print_info "后端API地址: http://localhost:8000"
    else
        print_error "服务启动失败，请检查日志"
        docker-compose logs
    fi
}

# 主函数
main() {
    print_info "开始安装部署..."
    
    check_commands
    create_directories
    build_frontend
    check_env
    check_ssl
    start_services
    check_services
    
    print_info "安装部署完成！"
}

# 执行主函数
main 