#!/bin/bash

# QAUP 配置管理脚本

set -e

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

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

print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 显示帮助信息
show_help() {
    echo "QAUP 配置管理脚本"
    echo ""
    echo "用法: $0 [命令] [选项]"
    echo ""
    echo "命令:"
    echo "  init        初始化配置文件"
    echo "  validate    验证配置文件"
    echo "  generate    生成配置文件"
    echo "  backup      备份配置文件"
    echo "  restore     恢复配置文件"
    echo "  encrypt     加密敏感配置"
    echo "  decrypt     解密敏感配置"
    echo "  show        显示当前配置"
    echo ""
    echo "示例:"
    echo "  $0 init                # 初始化配置"
    echo "  $0 validate            # 验证配置"
    echo "  $0 generate prod       # 生成生产环境配置"
}

# 初始化配置
init_config() {
    print_message $BLUE "初始化 QAUP 配置..."
    
    # 创建配置目录
    mkdir -p "$CONFIG_DIR"
    
    # 复制环境模板文件
    if [ ! -f "$ENV_FILE" ]; then
        if [ -f "$ENV_TEMPLATE" ]; then
            cp "$ENV_TEMPLATE" "$ENV_FILE"
            print_message $GREEN "环境配置文件已创建: $ENV_FILE"
            print_message $YELLOW "请编辑 $ENV_FILE 文件，修改相关配置"
        else
            print_message $RED "错误: 环境模板文件不存在: $ENV_TEMPLATE"
            exit 1
        fi
    else
        print_message $YELLOW "环境配置文件已存在: $ENV_FILE"
    fi
    
    # 创建必要的目录
    create_directories
    
    print_message $GREEN "配置初始化完成！"
}

# 创建必要的目录
create_directories() {
    local data_dir="./data"
    local log_dir="./logs"
    local backup_dir="./backup"
    local ssl_dir="./ssl"
    
    print_message $BLUE "创建必要的目录..."
    
    mkdir -p "$data_dir"/{postgres,redis,uploads}
    mkdir -p "$log_dir"/{postgres,redis,app,nginx}
    mkdir -p "$backup_dir"/{postgres,config}
    mkdir -p "$ssl_dir"
    
    # 设置目录权限
    chmod 755 "$data_dir" "$log_dir" "$backup_dir"
    chmod 700 "$data_dir"/postgres "$ssl_dir"
    
    print_message $GREEN "目录创建完成"
}

# 验证配置文件
validate_config() {
    print_message $BLUE "验证配置文件..."
    
    local errors=0
    
    # 检查环境文件
    if [ ! -f "$ENV_FILE" ]; then
        print_message $RED "错误: 环境文件不存在: $ENV_FILE"
        errors=$((errors + 1))
    else
        # 检查必需的环境变量
        source "$ENV_FILE"
        
        local required_vars=(
            "POSTGRES_DB"
            "POSTGRES_USER"
            "POSTGRES_PASSWORD"
            "APP_DB_USER"
            "APP_DB_PASSWORD"
        )
        
        for var in "${required_vars[@]}"; do
            if [ -z "${!var}" ]; then
                print_message $RED "错误: 必需的环境变量未设置: $var"
                errors=$((errors + 1))
            fi
        done
        
        # 检查密码强度
        if [ ${#POSTGRES_PASSWORD} -lt 8 ]; then
            print_message $YELLOW "警告: 数据库密码长度少于8位，建议使用更强的密码"
        fi
        
        if [ ${#APP_DB_PASSWORD} -lt 8 ]; then
            print_message $YELLOW "警告: 应用数据库密码长度少于8位，建议使用更强的密码"
        fi
    fi
    
    # 检查配置文件
    local config_files=(
        "$CONFIG_DIR/application-prod.yml"
    )
    
    for config_file in "${config_files[@]}"; do
        if [ ! -f "$config_file" ]; then
            print_message $YELLOW "警告: 配置文件不存在: $config_file"
        fi
    done
    
    if [ $errors -eq 0 ]; then
        print_message $GREEN "配置验证通过！"
        return 0
    else
        print_message $RED "配置验证失败，发现 $errors 个错误"
        return 1
    fi
}

# 生成配置文件
generate_config() {
    local env=${1:-prod}
    
    print_message $BLUE "生成 $env 环境配置文件..."
    
    if [ ! -f "$ENV_FILE" ]; then
        print_message $RED "错误: 环境文件不存在，请先运行 init 命令"
        exit 1
    fi
    
    source "$ENV_FILE"
    
    # 生成 Docker Compose 环境文件
    local compose_env_file="$PROJECT_ROOT/.env.compose"
    cat > "$compose_env_file" << EOF
# Docker Compose 环境配置
# 由配置管理脚本自动生成

# 数据库配置
POSTGRES_DB=$POSTGRES_DB
POSTGRES_USER=$POSTGRES_USER
POSTGRES_PASSWORD=$POSTGRES_PASSWORD
APP_DB_USER=$APP_DB_USER
APP_DB_PASSWORD=$APP_DB_PASSWORD

# Redis 配置
REDIS_PASSWORD=$REDIS_PASSWORD

# 应用配置
SPRING_PROFILES_ACTIVE=$SPRING_PROFILES_ACTIVE
APP_PORT=$APP_PORT

# Nginx 配置
NGINX_PORT=$NGINX_PORT
SERVER_NAME=$SERVER_NAME
API_PREFIX=$API_PREFIX
MAX_UPLOAD_SIZE=$MAX_UPLOAD_SIZE

# 目录配置
DATA_DIR=$DATA_DIR
LOG_DIR=$LOG_DIR
BACKUP_DIR=$BACKUP_DIR

# JVM 配置
JVM_OPTS=$JVM_OPTS
EOF
    
    print_message $GREEN "配置文件生成完成: $compose_env_file"
}

# 备份配置文件
backup_config() {
    local backup_dir="./backup/config"
    local timestamp=$(date +%Y%m%d_%H%M%S)
    local backup_file="config_backup_$timestamp.tar.gz"
    
    print_message $BLUE "备份配置文件..."
    
    mkdir -p "$backup_dir"
    
    # 创建备份
    tar -czf "$backup_dir/$backup_file" \
        -C "$PROJECT_ROOT" \
        .env \
        config/ \
        docker-compose*.yml \
        2>/dev/null || true
    
    print_message $GREEN "配置备份完成: $backup_dir/$backup_file"
}

# 显示当前配置
show_config() {
    print_message $BLUE "当前配置信息:"
    
    if [ -f "$ENV_FILE" ]; then
        echo ""
        echo "环境变量配置:"
        echo "=============="
        # 隐藏敏感信息
        grep -v "PASSWORD\|SECRET" "$ENV_FILE" | grep -v "^#" | grep -v "^$"
        echo ""
        echo "敏感配置项:"
        echo "==========="
        grep "PASSWORD\|SECRET" "$ENV_FILE" | sed 's/=.*/=***/' || echo "无敏感配置项"
    else
        print_message $RED "环境配置文件不存在"
    fi
}

# 加密敏感配置
encrypt_config() {
    print_message $BLUE "加密敏感配置..."
    
    if [ ! -f "$ENV_FILE" ]; then
        print_message $RED "错误: 环境文件不存在"
        exit 1
    fi
    
    # 创建加密版本
    local encrypted_file="$ENV_FILE.encrypted"
    
    # 使用 openssl 加密（需要输入密码）
    openssl enc -aes-256-cbc -salt -in "$ENV_FILE" -out "$encrypted_file"
    
    if [ $? -eq 0 ]; then
        print_message $GREEN "配置文件已加密: $encrypted_file"
        print_message $YELLOW "请妥善保管加密密码"
    else
        print_message $RED "配置文件加密失败"
        exit 1
    fi
}

# 解密敏感配置
decrypt_config() {
    print_message $BLUE "解密敏感配置..."
    
    local encrypted_file="$ENV_FILE.encrypted"
    
    if [ ! -f "$encrypted_file" ]; then
        print_message $RED "错误: 加密文件不存在: $encrypted_file"
        exit 1
    fi
    
    # 使用 openssl 解密
    openssl enc -aes-256-cbc -d -in "$encrypted_file" -out "$ENV_FILE"
    
    if [ $? -eq 0 ]; then
        print_message $GREEN "配置文件已解密: $ENV_FILE"
    else
        print_message $RED "配置文件解密失败"
        exit 1
    fi
}

# 主函数
main() {
    if [ $# -eq 0 ]; then
        show_help
        exit 0
    fi
    
    local command=$1
    shift
    
    case $command in
        init)
            init_config
            ;;
        validate)
            validate_config
            ;;
        generate)
            generate_config "$@"
            ;;
        backup)
            backup_config
            ;;
        show)
            show_config
            ;;
        encrypt)
            encrypt_config
            ;;
        decrypt)
            decrypt_config
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_message $RED "未知命令: $command"
            show_help
            exit 1
            ;;
    esac
}

main "$@"