#!/bin/bash

# Docker Compose 管理脚本

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(pwd)"
ENV_FILE="$PROJECT_ROOT/.env"

# 默认环境
ENVIRONMENT=${ENVIRONMENT:-prod}

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 显示帮助信息
show_help() {
    echo "QAUP Docker Compose 管理脚本"
    echo ""
    echo "用法: $0 [环境] [命令] [选项]"
    echo ""
    echo "环境:"
    echo "  dev     开发环境"
    echo "  prod    生产环境（默认）"
    echo ""
    echo "命令:"
    echo "  start   启动服务"
    echo "  stop    停止服务"
    echo "  restart 重启服务"
    echo "  status  查看服务状态"
    echo "  logs    查看服务日志"
    echo "  build   构建镜像"
    echo "  pull    拉取镜像"
    echo "  clean   清理资源"
    echo "  backup  备份数据"
    echo "  restore 恢复数据"
    echo ""
    echo "示例:"
    echo "  $0 prod start          # 启动生产环境"
    echo "  $0 dev logs qaup-app   # 查看开发环境应用日志"
    echo "  $0 prod backup         # 备份生产环境数据"
}

# 检查环境文件
check_env_file() {
    print_message $BLUE "检查环境文件: $ENV_FILE"
    if [ ! -f "$ENV_FILE" ]; then
        print_message $YELLOW "警告: 环境文件不存在，创建默认配置..."
        create_default_env
    else
        print_message $GREEN "✓ 环境文件存在: $ENV_FILE"
    fi
}

# 创建默认环境文件
create_default_env() {
    cat > "$ENV_FILE" << EOF
# QAUP Docker 部署环境配置

# 数据库配置
POSTGRES_DB=qaup
POSTGRES_USER=postgres
POSTGRES_PASSWORD=qaup123
APP_DB_USER=qaup_app
APP_DB_PASSWORD=qaup123

# Redis 配置
REDIS_PASSWORD=

# 应用配置
SPRING_PROFILES_ACTIVE=prod
APP_PORT=8080

# Nginx 配置
NGINX_PORT=80
NGINX_HTTPS_PORT=443
SERVER_NAME=localhost
API_PREFIX=/prod-api
MAX_UPLOAD_SIZE=20M

# 目录配置
DATA_DIR=../data
LOG_DIR=../logs
BACKUP_DIR=../backup

# JVM 配置
JVM_OPTS=-Dname=qaup-admin.jar -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m
EOF
    print_message $GREEN "默认环境文件已创建: $ENV_FILE"
}

# 获取 compose 文件参数
get_compose_files() {
    local env=$1
    
    # 使用项目根目录下的 docker-compose 文件
    local base_file="$PROJECT_ROOT/docker-compose.yml"
    local env_file="$PROJECT_ROOT/docker-compose.$env.yml"
    
    if [ -f "$env_file" ]; then
        echo "-f $base_file -f $env_file"
    else
        echo "-f $base_file"
    fi
}

# 创建必要的目录
create_directories() {
    local data_dir=${DATA_DIR:-../data}
    local log_dir=${LOG_DIR:-../logs}
    local backup_dir=${BACKUP_DIR:-../backup}
    
    print_message $BLUE "检查并创建必要的目录..."
    
    # 使用项目根目录下的目录结构，去掉 ../ 前缀
    local actual_data_dir=${data_dir#../}
    local actual_log_dir=${log_dir#../}
    local actual_backup_dir=${backup_dir#../}
    
    # 创建目录结构
    mkdir -p "$PROJECT_ROOT/$actual_data_dir"/{postgres,redis,uploads}
    mkdir -p "$PROJECT_ROOT/$actual_log_dir"/{postgres,redis,app,nginx}
    mkdir -p "$PROJECT_ROOT/$actual_backup_dir"/postgres
    
    # 只对新创建的基础目录设置权限，忽略已存在目录的权限错误
    for dir in "$PROJECT_ROOT/$actual_data_dir" "$PROJECT_ROOT/$actual_log_dir" "$PROJECT_ROOT/$actual_backup_dir"; do
        if [ -d "$dir" ]; then
            chmod 755 "$dir" 2>/dev/null || true
        fi
    done
    
    print_message $GREEN "目录检查完成！"
}

# 清理旧容器和占用的端口
cleanup_old_containers() {
    print_message $YELLOW "清理旧容器和占用的端口..."
    
    # 首先尝试停止可能存在的 docker-compose 服务
    cd "$PROJECT_ROOT"
    docker-compose $(get_compose_files prod) --env-file "$ENV_FILE" down 2>/dev/null || true
    
    # 停止并删除可能存在的旧容器
    local containers=("qaup-postgres" "qaup-redis" "qaup-app" "qaup-nginx")
    
    for container in "${containers[@]}"; do
        if docker ps -a --format "table {{.Names}}" | grep -q "^${container}$"; then
            print_message $BLUE "删除旧容器: $container"
            docker rm -f "$container" 2>/dev/null || true
        fi
    done
    
    # 清理可能占用端口的容器（通过端口查找）
    local ports=(5432 6379 8080 80 443)
    for port in "${ports[@]}"; do
        local container_id=$(docker ps --filter "publish=$port" -q 2>/dev/null || true)
        if [ -n "$container_id" ]; then
            print_message $BLUE "停止占用端口 $port 的容器: $container_id"
            docker rm -f "$container_id" 2>/dev/null || true
        fi
    done
    
    print_message $GREEN "旧容器和端口清理完成！"
}

# 启动服务
start_services() {
    local env=$1
    shift
    local services="$@"
    
    print_message $GREEN "启动 $env 环境服务..."
    check_env_file
    create_directories  # 智能创建目录，避免权限问题
    
    # 清理旧容器
    cleanup_old_containers
    
    cd "$PROJECT_ROOT"
    docker-compose $(get_compose_files $env) --env-file "$ENV_FILE" up -d $services
    
    print_message $GREEN "服务启动完成！"
    show_status $env
}

# 停止服务
stop_services() {
    local env=$1
    shift
    local services="$@"
    
    print_message $YELLOW "停止 $env 环境服务..."
    cd "$PROJECT_ROOT"
    docker-compose $(get_compose_files $env) --env-file "$ENV_FILE" stop $services
    
    print_message $GREEN "服务停止完成！"
}

# 重启服务
restart_services() {
    local env=$1
    shift
    local services="$@"
    
    print_message $BLUE "重启 $env 环境服务..."
    stop_services $env $services
    sleep 2
    start_services $env $services
}

# 查看服务状态
show_status() {
    local env=$1
    
    print_message $BLUE "查看 $env 环境服务状态..."
    cd "$PROJECT_ROOT"
    docker-compose $(get_compose_files $env) --env-file "$ENV_FILE" ps
}

# 查看日志
show_logs() {
    local env=$1
    shift
    local services="$@"
    
    cd "$PROJECT_ROOT"
    docker-compose $(get_compose_files $env) --env-file "$ENV_FILE" logs -f $services
}

# 构建镜像
build_images() {
    local env=$1
    
    print_message $BLUE "构建 $env 环境镜像..."
    cd "$PROJECT_ROOT"
    docker-compose $(get_compose_files $env) --env-file "$ENV_FILE" build
    
    print_message $GREEN "镜像构建完成！"
}

# 清理资源
clean_resources() {
    local env=$1
    
    print_message $YELLOW "清理 $env 环境资源..."
    cd "$PROJECT_ROOT"
    
    # 停止并删除容器
    docker-compose $(get_compose_files $env) --env-file "$ENV_FILE" down
    
    # 清理未使用的镜像和网络
    docker system prune -f
    
    print_message $GREEN "资源清理完成！"
}

# 备份数据
backup_data() {
    local env=$1
    
    print_message $BLUE "备份 $env 环境数据..."
    cd "$PROJECT_ROOT"
    
    # 执行数据库备份
    docker-compose $(get_compose_files $env) --env-file "$ENV_FILE" exec qaup-postgres /backup-db.sh
    
    print_message $GREEN "数据备份完成！"
}

# 主函数
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi
    
    # 解析参数
    local env="prod"
    local command=""
    
    # 检查第一个参数是否是环境
    if [[ "$1" =~ ^(dev|prod)$ ]]; then
        env=$1
        shift
    fi
    
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi
    
    command=$1
    shift
    
    # 加载环境文件
    if [ -f "$ENV_FILE" ]; then
        source "$ENV_FILE"
    fi
    
    # 执行命令
    case $command in
        start)
            start_services $env "$@"
            ;;
        stop)
            stop_services $env "$@"
            ;;
        restart)
            restart_services $env "$@"
            ;;
        status)
            show_status $env
            ;;
        logs)
            show_logs $env "$@"
            ;;
        build)
            build_images $env
            ;;
        clean)
            clean_resources $env
            ;;
        backup)
            backup_data $env
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_message $RED "未知命令: $command"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"