#!/bin/bash
# 部署并验证日志修复脚本
# 用于在服务器上部署更新的后端镜像并验证日志功能

set -e

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

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

# 检查是否在正确的目录
check_directory() {
    if [[ ! -f "deploy.sh" ]]; then
        log_error "请在部署目录中运行此脚本 (应包含 deploy.sh)"
        exit 1
    fi
}

# 停止后端服务
stop_backend() {
    log_info "停止后端服务..."
    ./deploy.sh stop backend -e production || true
    sleep 5
}

# 启动后端服务
start_backend() {
    log_info "启动后端服务..."
    ./deploy.sh start backend -e production
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 30
}

# 检查服务状态
check_service_status() {
    log_info "检查服务状态..."
    ./deploy.sh status backend -e production
}

# 检查日志目录
check_log_directories() {
    log_info "检查容器内日志目录..."
    
    # 检查 /app/logs 目录
    if docker exec anxin-backend-prod ls -la /app/logs 2>/dev/null; then
        log_success "✓ /app/logs 目录存在"
    else
        log_error "✗ /app/logs 目录不存在"
    fi
    
    # 检查符号链接
    if docker exec anxin-backend-prod ls -la /home/ruoyi/logs 2>/dev/null; then
        log_success "✓ /home/ruoyi/logs 符号链接存在"
    else
        log_error "✗ /home/ruoyi/logs 符号链接不存在"
    fi
    
    # 检查权限
    docker exec anxin-backend-prod ls -la /app/ | grep logs || true
    docker exec anxin-backend-prod ls -la /home/ruoyi/ | grep logs || true
}

# 检查启动日志
check_startup_logs() {
    log_info "检查启动日志..."
    
    # 显示最近的启动日志
    ./deploy.sh logs backend -e production --tail 50
    
    # 检查是否有日志错误
    if ./deploy.sh logs backend -e production --tail 100 | grep -i "Read-only file system"; then
        log_error "仍然存在只读文件系统错误"
        return 1
    else
        log_success "✓ 未发现只读文件系统错误"
    fi
    
    # 检查是否有其他日志相关错误
    if ./deploy.sh logs backend -e production --tail 100 | grep -i "FileNotFoundException.*logs"; then
        log_error "仍然存在日志文件未找到错误"
        return 1
    else
        log_success "✓ 未发现日志文件未找到错误"
    fi
}

# 测试日志文件创建
test_log_file_creation() {
    log_info "测试日志文件创建..."
    
    # 等待应用完全启动
    sleep 10
    
    # 检查日志文件是否被创建
    if docker exec anxin-backend-prod ls -la /app/logs/ 2>/dev/null | grep -E "\.(log|out)$"; then
        log_success "✓ 日志文件已创建"
        docker exec anxin-backend-prod ls -la /app/logs/
    else
        log_warn "日志文件可能还未创建，继续等待..."
        sleep 20
        if docker exec anxin-backend-prod ls -la /app/logs/ 2>/dev/null | grep -E "\.(log|out)$"; then
            log_success "✓ 日志文件已创建"
            docker exec anxin-backend-prod ls -la /app/logs/
        else
            log_error "✗ 日志文件未创建"
        fi
    fi
}

# 运行诊断脚本
run_diagnostics() {
    log_info "运行日志诊断脚本..."
    
    # 复制诊断脚本到容器
    if [[ -f "scripts/fix-logging-issues.sh" ]]; then
        docker cp scripts/fix-logging-issues.sh anxin-backend-prod:/tmp/
        docker exec anxin-backend-prod chmod +x /tmp/fix-logging-issues.sh
        docker exec anxin-backend-prod /tmp/fix-logging-issues.sh check
    else
        log_warn "诊断脚本不存在，跳过诊断"
    fi
}

# 检查应用健康状态
check_application_health() {
    log_info "检查应用健康状态..."
    
    # 等待健康检查
    sleep 30
    
    # 检查容器健康状态
    if docker ps --filter "name=anxin-backend-prod" --format "table {{.Names}}\t{{.Status}}" | grep -i healthy; then
        log_success "✓ 应用健康检查通过"
    else
        log_warn "应用健康检查状态未知，检查详细状态..."
        docker ps --filter "name=anxin-backend-prod"
    fi
}

# 显示部署总结
show_summary() {
    echo ""
    log_info "=== 部署验证总结 ==="
    echo "----------------------------------------"
    
    # 服务状态
    echo "服务状态:"
    ./deploy.sh status backend -e production | grep -E "(anxin-backend-prod|State|Health)" || true
    
    echo ""
    echo "日志目录:"
    docker exec anxin-backend-prod ls -la /app/logs/ 2>/dev/null | head -10 || echo "无法访问日志目录"
    
    echo ""
    echo "最近日志 (最后10行):"
    ./deploy.sh logs backend -e production --tail 10 || true
    
    echo "----------------------------------------"
    log_info "如果仍有问题，请检查:"
    echo "1. 容器启动日志: ./deploy.sh logs backend -e production"
    echo "2. 容器内部状态: docker exec -it anxin-backend-prod /bin/bash"
    echo "3. 日志目录权限: docker exec anxin-backend-prod ls -la /app/logs /home/ruoyi/logs"
}

# 主函数
main() {
    log_info "开始部署并验证日志修复..."
    echo "========================================"
    
    # 检查环境
    check_directory
    
    # 停止服务
    stop_backend
    
    # 启动服务
    start_backend
    
    # 检查服务状态
    check_service_status
    
    # 检查日志目录
    check_log_directories
    
    # 检查启动日志
    if check_startup_logs; then
        log_success "启动日志检查通过"
    else
        log_error "启动日志检查失败"
    fi
    
    # 测试日志文件创建
    test_log_file_creation
    
    # 运行诊断
    run_diagnostics
    
    # 检查应用健康
    check_application_health
    
    # 显示总结
    show_summary
    
    echo "========================================"
    log_success "部署验证完成!"
}

# 如果脚本被直接执行
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi