#!/bin/bash

# QAUP Docker 镜像版本同步更新脚本
# 根据 image-versions.env 配置文件更新所有相关文件中的镜像版本

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
IMAGE_VERSIONS_FILE="$SCRIPT_DIR/image-versions.env"

# 颜色输出
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 Docker 镜像版本同步更新脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help     显示帮助信息"
    echo "  --dry-run      仅显示将要进行的更改，不实际修改文件"
    echo "  --backup       更新前备份原文件"
    echo ""
    echo "功能:"
    echo "  - 从 image-versions.env 读取最新版本配置"
    echo "  - 更新 docker-compose.yml 中的镜像版本"
    echo "  - 更新 Dockerfile 中的基础镜像版本"
    echo "  - 生成版本更新报告"
}

# 检查参数
DRY_RUN=false
BACKUP=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            exit 0
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --backup)
            BACKUP=true
            shift
            ;;
        *)
            echo "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
done

# 检查配置文件
if [ ! -f "$IMAGE_VERSIONS_FILE" ]; then
    print_message $RED "错误: 镜像版本配置文件不存在: $IMAGE_VERSIONS_FILE"
    exit 1
fi

# 加载配置
source "$IMAGE_VERSIONS_FILE"

print_message $BLUE "========================================="
print_message $BLUE "QAUP Docker 镜像版本同步更新"
print_message $BLUE "========================================="
echo ""

if [ "$DRY_RUN" = true ]; then
    print_message $YELLOW "运行模式: 预览模式（不会实际修改文件）"
else
    print_message $GREEN "运行模式: 更新模式"
fi
echo ""

# 备份函数
backup_file() {
    local file=$1
    if [ "$BACKUP" = true ] && [ -f "$file" ]; then
        local backup_file="${file}.backup.$(date +%Y%m%d_%H%M%S)"
        cp "$file" "$backup_file"
        print_message $GREEN "已备份: $file -> $backup_file"
    fi
}

# 更新 docker-compose.yml
update_docker_compose() {
    local compose_file="$PROJECT_ROOT/docker-compose.yml"
    
    if [ ! -f "$compose_file" ]; then
        print_message $YELLOW "警告: docker-compose.yml 不存在，跳过更新"
        return
    fi
    
    print_message $BLUE "更新 docker-compose.yml..."
    
    # 检查当前版本
    local current_postgres=$(grep -A 1 "qaup-postgres:" "$compose_file" | grep "image:" | awk '{print $2}' | head -1)
    local current_redis=$(grep -A 1 "qaup-redis:" "$compose_file" | grep "image:" | awk '{print $2}' | head -1)
    
    echo "PostgreSQL: $current_postgres -> $POSTGRES_IMAGE"
    echo "Redis: $current_redis -> $REDIS_IMAGE"
    
    if [ "$DRY_RUN" = false ]; then
        backup_file "$compose_file"
        
        # 更新 PostgreSQL 镜像
        sed -i.tmp "s|image: postgis/postgis:.*|image: $POSTGRES_IMAGE|g" "$compose_file"
        
        # 更新 Redis 镜像
        sed -i.tmp "s|image: redis:.*|image: $REDIS_IMAGE|g" "$compose_file"
        
        # 清理临时文件
        rm -f "${compose_file}.tmp"
        
        print_message $GREEN "✓ docker-compose.yml 更新完成"
    fi
    echo ""
}

# 更新 Dockerfile
update_dockerfile() {
    local dockerfile="$PROJECT_ROOT/Dockerfile"
    
    if [ ! -f "$dockerfile" ]; then
        print_message $YELLOW "警告: Dockerfile 不存在，跳过更新"
        return
    fi
    
    print_message $BLUE "更新 Dockerfile..."
    
    # 检查当前版本
    local current_maven=$(grep "^FROM maven:" "$dockerfile" | awk '{print $2}' | head -1)
    local current_openjdk=$(grep "^FROM openjdk:" "$dockerfile" | awk '{print $2}' | head -1)
    
    echo "Maven: $current_maven -> $MAVEN_IMAGE"
    echo "OpenJDK: $current_openjdk -> $OPENJDK_IMAGE"
    
    if [ "$DRY_RUN" = false ]; then
        backup_file "$dockerfile"
        
        # 更新 Maven 镜像
        sed -i.tmp "s|FROM maven:.*AS builder|FROM $MAVEN_IMAGE AS builder|g" "$dockerfile"
        
        # 更新 OpenJDK 镜像
        sed -i.tmp "s|FROM openjdk:.*|FROM $OPENJDK_IMAGE|g" "$dockerfile"
        
        # 清理临时文件
        rm -f "${dockerfile}.tmp"
        
        print_message $GREEN "✓ Dockerfile 更新完成"
    fi
    echo ""
}

# 更新 Nginx Dockerfile
update_nginx_dockerfile() {
    local nginx_dockerfile="$PROJECT_ROOT/docker/nginx/Dockerfile"
    
    if [ ! -f "$nginx_dockerfile" ]; then
        print_message $YELLOW "警告: Nginx Dockerfile 不存在，跳过更新"
        return
    fi
    
    print_message $BLUE "更新 Nginx Dockerfile..."
    
    # 检查当前版本
    local current_node=$(grep "^FROM node:" "$nginx_dockerfile" | awk '{print $2}' | head -1)
    local current_nginx=$(grep "^FROM nginx:" "$nginx_dockerfile" | awk '{print $2}' | head -1)
    
    echo "Node.js: $current_node -> $NODE_IMAGE"
    echo "Nginx: $current_nginx -> $NGINX_IMAGE"
    
    if [ "$DRY_RUN" = false ]; then
        backup_file "$nginx_dockerfile"
        
        # 更新 Node.js 镜像
        sed -i.tmp "s|FROM node:.*AS frontend-builder|FROM $NODE_IMAGE AS frontend-builder|g" "$nginx_dockerfile"
        
        # 更新 Nginx 镜像
        sed -i.tmp "s|FROM nginx:.*|FROM $NGINX_IMAGE|g" "$nginx_dockerfile"
        
        # 清理临时文件
        rm -f "${nginx_dockerfile}.tmp"
        
        print_message $GREEN "✓ Nginx Dockerfile 更新完成"
    fi
    echo ""
}

# 生成更新报告
generate_report() {
    local report_file="$PROJECT_ROOT/image-version-update-report.txt"
    
    cat > "$report_file" << EOF
QAUP Docker 镜像版本更新报告
生成时间: $(date)
更新模式: $([ "$DRY_RUN" = true ] && echo "预览模式" || echo "实际更新")

更新的镜像版本:
- PostgreSQL/PostGIS: $POSTGRES_IMAGE
- Redis: $REDIS_IMAGE
- Maven: $MAVEN_IMAGE
- OpenJDK: $OPENJDK_IMAGE
- Nginx: $NGINX_IMAGE
- Node.js: $NODE_IMAGE

更新的文件:
- docker-compose.yml
- Dockerfile
- docker/nginx/Dockerfile

后续操作建议:
1. 测试新版本的兼容性
2. 更新离线部署镜像包
3. 更新部署文档中的版本信息
4. 在测试环境验证后再部署到生产环境
EOF

    print_message $GREEN "更新报告已生成: $report_file"
}

# 执行更新
print_message $BLUE "开始更新镜像版本..."
echo ""

update_docker_compose
update_dockerfile
update_nginx_dockerfile

if [ "$DRY_RUN" = false ]; then
    print_message $GREEN "========================================="
    print_message $GREEN "镜像版本更新完成！"
    print_message $GREEN "========================================="
    echo ""
    print_message $YELLOW "重要提醒:"
    echo "1. 请在测试环境验证新版本的兼容性"
    echo "2. 运行 ./prepare-offline-images.sh 更新离线部署包"
    echo "3. 考虑更新相关文档中的版本信息"
else
    print_message $BLUE "========================================="
    print_message $BLUE "预览完成（未实际修改文件）"
    print_message $BLUE "========================================="
    echo ""
    print_message $YELLOW "如需实际更新，请运行: $0"
fi

generate_report