#!/bin/bash

# 一键式环境检测与应用部署脚本
# 用法: ./bash.sh

# 处理SSH首次连接认证
echo "===== 处理SSH首次连接认证 ====="
# 创建SSH配置目录
mkdir -p ~/.ssh
chmod 700 ~/.ssh

# 禁用SSH首次连接时的主机密钥检查
if [ ! -f ~/.ssh/config ]; then
    echo "创建SSH配置文件..."
    cat > ~/.ssh/config << EOF
Host *
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
EOF
    chmod 600 ~/.ssh/config
    echo "✓ SSH配置已完成"
fi

# 错误处理和回滚机制
set -e  # 遇到错误立即退出

# 定义回滚状态变量
INSTALLED_PACKAGES=""
CREATED_DIRS=""
CREATED_FILES=""
DOWNLOADED_FILES=""
SERVICE_STARTED=false
NGINX_CONFIGURED=false
DATABASE_CREATED=false
ORIGINAL_NGINX_CONFIG=""
BACKUP_DIR="/tmp/fish_deploy_backup_$(date +%Y%m%d%H%M%S)"

# 创建备份目录
mkdir -p "$BACKUP_DIR"

# 回滚函数
rollback() {
    echo ""
    echo "===== 执行回滚操作 ====="
    echo "错误发生在: $1"
    
    # 停止并移除服务
    if [ "$SERVICE_STARTED" = true ]; then
        echo "停止并禁用后端服务..."
        systemctl stop fish-backend 2>/dev/null || true
        systemctl disable fish-backend 2>/dev/null || true
        rm -f /etc/systemd/system/fish-backend.service 2>/dev/null || true
        systemctl daemon-reload
    fi
    
    # 回滚数据库
    if [ "$DATABASE_CREATED" = true ]; then
        echo "尝试删除创建的数据库..."
        if [ -n "$MYSQL_PASSWORD" ]; then
            mysql -u root -p"$MYSQL_PASSWORD" -e "DROP DATABASE IF EXISTS fish" 2>/dev/null || true
        fi
    fi
    
    # 回滚Nginx配置
    if [ "$NGINX_CONFIGURED" = true ]; then
        echo "回滚Nginx配置..."
        if [ -f "$NGINX_CONF_FILE" ]; then
            rm -f "$NGINX_CONF_FILE" 2>/dev/null || true
        fi
        if [ -n "$ORIGINAL_NGINX_CONFIG" ] && [ -f "$ORIGINAL_NGINX_CONFIG" ]; then
            # 恢复原始配置
            cat "$ORIGINAL_NGINX_CONFIG" > "$NGINX_CONF_FILE" 2>/dev/null || true
        fi
        # 重启Nginx
        if command -v systemctl &> /dev/null; then
            systemctl restart nginx 2>/dev/null || true
        elif [ -f "/etc/init.d/nginx" ]; then
            /etc/init.d/nginx restart 2>/dev/null || true
        fi
    fi
    
    # 删除已下载/创建的文件
    for file in $DOWNLOADED_FILES; do
        if [ -f "$file" ]; then
            echo "删除下载的文件: $file"
            rm -f "$file" 2>/dev/null || true
        fi
    done
    
    # 删除已创建的文件
    for file in $CREATED_FILES; do
        if [ -f "$file" ]; then
            echo "删除创建的文件: $file"
            rm -f "$file" 2>/dev/null || true
        fi
    done
    
    # 删除创建的目录（倒序删除以确保子目录先删除）
    REVERSED_DIRS=$(echo "$CREATED_DIRS" | tr ' ' '\n' | tac | tr '\n' ' ')
    for dir in $REVERSED_DIRS; do
        if [ -d "$dir" ]; then
            echo "删除创建的目录: $dir"
            rm -rf "$dir" 2>/dev/null || true
        fi
    done
    
    echo "回滚完成。系统已尽可能恢复到部署前状态。"
    exit 1
}

# 设置错误陷阱
trap 'rollback "脚本执行过程中发生未知错误"' ERR

# 记录函数
record_install() {
    INSTALLED_PACKAGES="$INSTALLED_PACKAGES $1"
}

record_dir() {
    CREATED_DIRS="$CREATED_DIRS $1"
}

record_file() {
    CREATED_FILES="$CREATED_FILES $1"
}

record_download() {
    DOWNLOADED_FILES="$DOWNLOADED_FILES $1"
}

# 检查操作结果
check_result() {
    if [ $? -ne 0 ]; then
        rollback "$1"
    fi
}

echo "===== 一键式环境检测与应用部署 ====="
echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# 检查是否为root用户
if [ "$(id -u)" != "0" ]; then
   echo "错误: 必须以root用户运行此脚本"
   exit 1
fi

# 设置应用信息
APP_DIR="/www/wwwroot/messages"
FRONTEND_DIR="$APP_DIR/web/dist"
BACKEND_JAR="$APP_DIR/background/cross-border-commerce-1.0-SNAPSHOT.jar"
SQL_FILE="$APP_DIR/fish.sql"
DEFAULT_MYSQL_PASSWORD="Guan@1026"

# 检测并安装解压软件
echo "===== 步骤1: 检测并安装解压软件 ====="
if ! command -v unzip &> /dev/null; then
    echo "未安装unzip工具，开始安装..."
    if command -v apt-get &> /dev/null; then
        apt-get update && apt-get install -y unzip
    elif command -v yum &> /dev/null; then
        yum install -y unzip
    else
        echo "× 错误: 无法自动安装unzip，请手动安装"
        exit 1
    fi
    
    # 再次验证安装结果
    if command -v unzip &> /dev/null; then
        echo "✓ unzip安装成功"
    else
        echo "× 错误: unzip安装失败，请手动安装"
        exit 1
    fi
else
    echo "✓ unzip工具已安装"
fi

# 检测并安装Java
echo "===== 步骤2: 检测并安装Java ====="
if ! command -v java &> /dev/null; then
    echo "未检测到Java，正在安装JDK 1.8..."
    if command -v apt-get &> /dev/null; then
        apt-get update && apt-get install -y openjdk-8-jdk
    elif command -v yum &> /dev/null; then
        yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel
    else
        echo "× 错误: 无法自动安装Java，请手动安装JDK 1.8或更高版本"
        exit 1
    fi
    
    # 验证Java安装结果
    if command -v java &> /dev/null; then
        java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
        echo "✓ Java安装成功，版本: $java_version"
    else
        echo "× 错误: Java安装失败，请手动安装"
        exit 1
    fi
else
    java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
    echo "✓ 检测到Java版本: $java_version"
fi

# 检测并安装Nginx
echo "===== 步骤3: 检测并安装Nginx ====="
if ! command -v nginx &> /dev/null; then
    echo "未检测到Nginx，正在安装..."
    if command -v apt-get &> /dev/null; then
        apt-get update && apt-get install -y nginx
    elif command -v yum &> /dev/null; then
        yum install -y epel-release
        yum install -y nginx
    else
        echo "× 错误: 无法自动安装Nginx，请手动安装"
        exit 1
    fi
    
    # 启动Nginx
    systemctl start nginx
    systemctl enable nginx
    
    # 验证Nginx安装结果
    if command -v nginx &> /dev/null; then
        nginx_version=$(nginx -v 2>&1 | awk -F/ '{print $2}')
        echo "✓ Nginx安装成功，版本: $nginx_version"
    else
        echo "× 错误: Nginx安装失败，请手动安装"
        exit 1
    fi
else
    nginx_version=$(nginx -v 2>&1 | awk -F/ '{print $2}')
    echo "✓ 检测到Nginx版本: $nginx_version"
fi

# 安装certbot
# echo "===== 步骤3.1: 安装certbot ====="
# # 卸载所有 python2 相关的 certbot 及依赖，避免依赖冲突
# if command -v yum &> /dev/null; then
#     yum remove -y certbot python2-certbot* python-certbot* python2-urllib3 python-urllib3 python2-requests python-requests python2-acme python-requests-toolbelt
#     # 手动删除冲突文件
#     rm -rf /usr/lib/python2.7/site-packages/urllib3
# elif command -v apt-get &> /dev/null; then
#     apt-get remove -y certbot python-certbot* python-urllib3 python-requests
# fi

# # 安装新版certbot（python3版）
# if ! command -v certbot &> /dev/null; then
#     echo "未检测到certbot，正在安装..."
#     if command -v apt-get &> /dev/null; then
#         # Debian/Ubuntu系统
#         apt-get update
#         apt-get install -y python3 python3-pip
#         apt-get install -y certbot python3-certbot-nginx
#     elif command -v yum &> /dev/null; then
#         # CentOS/RHEL系统
#         yum install -y epel-release
#         yum install -y python3
#         yum install -y certbot python3-certbot-nginx
#     else
#         echo "× 错误: 无法自动安装certbot，请手动安装"
#         exit 1
#     fi
    
#     # 验证certbot安装
#     if command -v certbot &> /dev/null; then
#         certbot_version=$(certbot --version 2>&1 | head -n 1)
#         echo "✓ certbot安装成功，版本: $certbot_version"
#     else
#         echo "× 错误: certbot安装失败，请手动安装"
#         exit 1
#     fi
# else
#     certbot_version=$(certbot --version 2>&1 | head -n 1)
#     echo "✓ 检测到certbot版本: $certbot_version"
# fi

# 检测并安装MySQL
# 检测并安装MySQL (Docker方式)
#!/bin/bash

#!/bin/bash

#!/bin/bash
#!/bin/bash

# 配置项
echo "===== 步骤4: 安装数据库 ====="

# 配置项
MYSQL_TAR="mysql-5.7.16-1.el7.x86_64.rpm-bundle.tar"
INSTALL_DIR="/opt"
LOG_FILE="/var/log/mysql_install.log"
PASSWORD_FILE="/root/mysql_root_password.txt"
WORKDIR="/www/wwwroot/messages"

# 生成满足 MySQL validate_password MEDIUM 策略的密码
generate_secure_password() {
    local upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    local lower="abcdefghijklmnopqrstuvwxyz"
    local digit="0123456789"
    local symbol='!@#$%^&*()_+-=[]{};:,.<>?'

    local password=""
    password+="${upper:RANDOM%${#upper}:1}"
    password+="${lower:RANDOM%${#lower}:1}"
    password+="${digit:RANDOM%${#digit}:1}"
    password+="${symbol:RANDOM%${#symbol}:1}"

    local all="${upper}${lower}${digit}${symbol}"
    for (( i=4; i<16; i++ )); do
        password+="${all:RANDOM%${#all}:1}"
    done

    echo "$password" | fold -w1 | shuf | tr -d '\n'
    echo
}

# 日志记录函数
log_info() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 初始化日志文件
echo "===== MySQL安装开始 [$(date '+%Y-%m-%d %H:%M:%S')] =====" | tee "$LOG_FILE"

# 检查是否已安装 MySQL
if rpm -qa | grep -q mysql-community-server; then
    log_info "⚠️ 检测到 MySQL 已安装，跳过安装步骤"

    # 获取密码文件并显示提示
    if [ -f "$PASSWORD_FILE" ]; then
        log_info "🔐 MySQL root 密码文件已存在：$PASSWORD_FILE"
    else
        log_info "⚠️ 找不到 root 密码文件，请手动检查 /var/log/mysqld.log 或重置密码"
    fi

    cd "$WORKDIR" || {
        log_info "❌ 无法进入工作目录 $WORKDIR"
        exit 1
    }

    log_info "📂 已进入工作目录 $WORKDIR"
else
    # 安装流程
    log_info "安装依赖库..."
    yum -y install libaio net-tools wget || {
        log_info "依赖安装失败!"
        exit 1
    }

    cd "$INSTALL_DIR" || {
        log_info "无法进入安装目录 $INSTALL_DIR"
        exit 1
    }

    log_info "下载 MySQL 安装包..."
    wget -c "https://cdn.mysql.com/archives/mysql-5.7/$MYSQL_TAR" || {
        log_info "下载失败!"
        exit 1
    }

    log_info "解压安装包..."
    tar -xvf "$MYSQL_TAR" || {
        log_info "解压失败!"
        exit 1
    }

    log_info "移除冲突包 mariadb..."
    yum remove -y mariadb-libs 2>/dev/null

    log_info "导入 GPG 密钥..."
    rpm --import https://repo.mysql.com/RPM-GPG-KEY-mysql || {
        log_info "GPG 密钥导入失败!"
        exit 1
    }

    log_info "安装 MySQL 组件..."
    for pkg in common libs client server; do
        rpm -ivh "mysql-community-${pkg}-5.7.16-1.el7.x86_64.rpm" || {
            log_info "安装 mysql-community-${pkg} 失败!"
            exit 1
        }
    done

    log_info "启动 MySQL 服务..."
    systemctl enable mysqld
    systemctl start mysqld || {
        log_info "服务启动失败!"
        exit 1
    }

    log_info "设置 root 密码..."
    TEMP_PASS=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')
    MYSQL_ROOT_PASS=$(generate_secure_password)

    mysql --connect-expired-password -uroot -p"$TEMP_PASS" -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASS';"
    [ $? -ne 0 ] && {
        log_info "密码修改失败!"
        exit 1
    }

    mysql -uroot -p"$MYSQL_ROOT_PASS" <<EOF
UNINSTALL PLUGIN validate_password;
FLUSH PRIVILEGES;
EOF

    echo "$MYSQL_ROOT_PASS" > "$PASSWORD_FILE"
    chmod 600 "$PASSWORD_FILE"
    log_info "✅ MySQL root 密码已保存至 $PASSWORD_FILE"

    cd "$WORKDIR" || {
        log_info "❌ 无法进入工作目录 $WORKDIR"
        exit 1
    }

    log_info "📂 已进入工作目录 $WORKDIR"
    log_info "✅ MySQL 5.7 安装完成"
    echo "===== MySQL安装成功完成 =====" | tee -a "$LOG_FILE"
    echo "MySQL版本: 5.7.16" | tee -a "$LOG_FILE"
    echo "Root密码: $MYSQL_ROOT_PASS" | tee -a "$LOG_FILE"
    echo "连接命令: mysql -uroot -p'$MYSQL_ROOT_PASS'" | tee -a "$LOG_FILE"
    echo "安装日志: $LOG_FILE" | tee -a "$LOG_FILE"
    rm -f "$MYSQL_TAR"
    log_info "清理安装包完成"
fi

# === 此处继续脚本的下一部分 ===
echo "===== 步骤5: 创建应用目录 ====="

if [ ! -d "$APP_DIR" ]; then
    echo "创建应用根目录: $APP_DIR"
    mkdir -p "$APP_DIR"
    check_result "创建应用根目录失败"
    record_dir "$APP_DIR"
    echo "✓ 应用根目录已创建"
else
    echo "✓ 应用根目录已存在"
fi

# 创建前端目录
if [ ! -d "$FRONTEND_DIR" ]; then
    echo "创建前端目录: $FRONTEND_DIR"
    mkdir -p "$FRONTEND_DIR"
    echo "✓ 前端目录已创建"
else
    echo "✓ 前端目录已存在"
fi

# 创建后端目录
BACKEND_DIR=$(dirname "$BACKEND_JAR")
if [ ! -d "$BACKEND_DIR" ]; then
    echo "创建后端目录: $BACKEND_DIR"
    mkdir -p "$BACKEND_DIR"
    echo "✓ 后端目录已创建"
else
    echo "✓ 后端目录已存在"
fi

# 设置下载地址
BACKEND_URL="http://8.219.83.91:8082/background/cross-border-commerce-1.0-SNAPSHOT.jar"
WEB_ZIP_URL="http://8.219.83.91:8082/web.zip"
SQL_URL="http://8.219.83.91:8082/fish.sql"
UPDATE_SCRIPT_URL="http://8.219.83.91:8082/update.sh"

# 下载更新脚本
download_update_script() {
    echo -e "${YELLOW}正在下载更新脚本...${NC}"
    # 获取当前脚本所在目录
    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    wget "$UPDATE_SCRIPT_URL" -O "$SCRIPT_DIR/update.sh"
    if [ $? -eq 0 ]; then
        chmod +x "$SCRIPT_DIR/update.sh"
        echo -e "${GREEN}更新脚本已下载到 $SCRIPT_DIR/update.sh${NC}"
    else
        echo -e "${RED}更新脚本下载失败${NC}"
    fi
}

# 下载并解压资源文件
echo "===== 步骤5.1: 下载应用资源 ====="

# 下载后端JAR文件
echo "正在下载后端JAR文件..."
if command -v curl &> /dev/null; then
    curl -L -o "$BACKEND_JAR" "$BACKEND_URL"
    BACKEND_DOWNLOAD=$?
elif command -v wget &> /dev/null; then
    wget -O "$BACKEND_JAR" "$BACKEND_URL"
    BACKEND_DOWNLOAD=$?
else
    echo "× 错误: 未安装curl或wget，无法下载后端文件"
    BACKEND_DOWNLOAD=1
fi

if [ $BACKEND_DOWNLOAD -eq 0 ] && [ -f "$BACKEND_JAR" ]; then
    echo "✓ 后端JAR文件下载成功"
    chmod +x "$BACKEND_JAR"
else
    echo "× 错误: 后端JAR文件下载失败"
fi

# 下载前端ZIP文件
echo "正在下载前端ZIP文件..."
if command -v curl &> /dev/null; then
    curl -L -o web.zip "$WEB_ZIP_URL"
    WEB_DOWNLOAD=$?
elif command -v wget &> /dev/null; then
    wget -O web.zip "$WEB_ZIP_URL"
    WEB_DOWNLOAD=$?
else
    echo "× 错误: 未安装curl或wget，无法下载前端文件"
    WEB_DOWNLOAD=1
fi

# 解压前端文件
if [ $WEB_DOWNLOAD -eq 0 ] && [ -f "web.zip" ]; then
    echo "✓ 前端ZIP文件下载成功，开始解压..."
    # 确保unzip已安装
    if command -v unzip &> /dev/null; then
        # 解压到前端目录
        unzip -o web.zip -d "$APP_DIR"
        if [ $? -eq 0 ]; then
            echo "✓ 前端文件解压成功"
            # 确保权限正确
            chmod -R 755 "$FRONTEND_DIR"
        else
            echo "× 错误: 前端文件解压失败"
        fi
    else
        echo "× 错误: 未安装unzip工具，无法解压前端文件"
    fi
else
    echo "× 错误: 前端ZIP文件下载失败"
fi

# 下载SQL文件
echo "正在下载SQL文件..."
if command -v curl &> /dev/null; then
    curl -L -o "$SQL_FILE" "$SQL_URL"
    SQL_DOWNLOAD=$?
elif command -v wget &> /dev/null; then
    wget -O "$SQL_FILE" "$SQL_URL"
    SQL_DOWNLOAD=$?
else
    echo "× 错误: 未安装curl或wget，无法下载SQL文件"
    SQL_DOWNLOAD=1
fi

if [ $SQL_DOWNLOAD -eq 0 ] && [ -f "$SQL_FILE" ]; then
    echo "✓ SQL文件下载成功"
    record_download "$SQL_FILE"
    
    # 修复SQL文件中的排序规则
    echo "正在修复SQL文件中的MySQL 5.7兼容性问题..."
    # 备份原始SQL文件
    cp "$SQL_FILE" "${SQL_FILE}.bak"
    # 替换排序规则
    sed -i 's/utf8mb4_0900_ai_ci/utf8mb4_general_ci/g' "$SQL_FILE"
    # 修复create_time的默认值问题
    sed -i 's/DEFAULT CURRENT_TIMESTAMP/DEFAULT "2023-01-01 00:00:00"/g' "$SQL_FILE"
    # 修复update_time的ON UPDATE子句问题
    sed -i 's/ON UPDATE CURRENT_TIMESTAMP//g' "$SQL_FILE"
    echo "✓ SQL文件修复完成"
else
    echo "× 错误: SQL文件下载失败"
fi

# 初始化数据库
#!/bin/bash

# 配置项
SQL_FILE="${1:-fish.sql}"  # 默认参数
DB_NAME="fish"
MYSQL_USER="root"
MYSQL_PASSWORD=$(cat /root/mysql_root_password.txt)
DOCKER_MODE=false

# 日志输出
LOG_FILE="/var/log/mysql_db_init.log"
echo "===== 数据库初始化开始 [$(date '+%Y-%m-%d %H:%M:%S')] =====" | tee "$LOG_FILE"

# 判断是否在 Docker 中运行
if docker info > /dev/null 2>&1; then
    if docker ps --format '{{.Names}}' | grep -q '^mysql57$'; then
        DOCKER_MODE=true
        MYSQL_CMD="docker exec mysql57 mysql"
    fi
fi

# 检查 SQL 文件是否存在
if [ ! -f "$SQL_FILE" ]; then
    echo "× 错误: SQL 文件不存在: $SQL_FILE" | tee -a "$LOG_FILE"
    exit 1
fi

# 获取 root 密码
if [ -z "$MYSQL_PASSWORD" ]; then
    echo "× 错误: 未找到 root 密码" | tee -a "$LOG_FILE"
    exit 1
fi

# 修复 SQL 兼容性
echo "正在修复SQL文件兼容性问题..." | tee -a "$LOG_FILE"
cp "$SQL_FILE" "${SQL_FILE}.bak"
sed -i 's/utf8mb4_0900_ai_ci/utf8mb4_general_ci/g' "$SQL_FILE"
sed -i 's/DEFAULT CURRENT_TIMESTAMP/DEFAULT "2023-01-01 00:00:00"/g' "$SQL_FILE"
sed -i 's/ON UPDATE CURRENT_TIMESTAMP//g' "$SQL_FILE"
echo "✓ SQL文件修复完成" | tee -a "$LOG_FILE"

# 检查数据库是否存在
if $DOCKER_MODE; then
    DB_EXISTS=$(docker exec mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -sN -e "SHOW DATABASES LIKE '$DB_NAME'")
else
    DB_EXISTS=$(mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -sN -e "SHOW DATABASES LIKE '$DB_NAME'")
fi

if [ "$DB_EXISTS" = "$DB_NAME" ]; then
    echo "$DB_NAME 数据库已存在，检查是否需要重新初始化" | tee -a "$LOG_FILE"

    TABLE_COUNT=$(
        if $DOCKER_MODE; then
            docker exec mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -sN -e "SELECT COUNT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA='$DB_NAME'"
        else
            mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -sN -e "SELECT COUNT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA='$DB_NAME'"
        fi
    )

    if [ "$TABLE_COUNT" -gt "0" ]; then
        read -p "数据库已包含 $TABLE_COUNT 个数据表，是否重新初始化？[y/N]: " REINIT
        if [[ "$REINIT" =~ ^[Yy]$ ]]; then
            echo "重新初始化数据库..." | tee -a "$LOG_FILE"
            if $DOCKER_MODE; then
                docker exec mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "DROP DATABASE $DB_NAME"
                docker exec mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"
                docker exec -i mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
            else
                mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "DROP DATABASE $DB_NAME"
                mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"
                mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
            fi
            echo "✓ 数据库重新初始化完成" | tee -a "$LOG_FILE"
        else
            echo "保留现有数据库，跳过初始化" | tee -a "$LOG_FILE"
        fi
    else
        echo "数据库存在但无表，初始化数据库..." | tee -a "$LOG_FILE"
        if $DOCKER_MODE; then
            docker exec -i mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
        else
            mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
        fi
        echo "✓ 数据库初始化完成" | tee -a "$LOG_FILE"
    fi
else
    echo "创建 $DB_NAME 数据库并初始化..." | tee -a "$LOG_FILE"
    if $DOCKER_MODE; then
        docker exec mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"
        docker exec -i mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
    else
        mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"
        mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
    fi
    echo "✓ 数据库初始化完成" | tee -a "$LOG_FILE"
fi

# 验证数据库初始化
if $DOCKER_MODE; then
    TABLE_COUNT_AFTER=$(docker exec mysql57 mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -sN -e "SELECT COUNT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA='$DB_NAME'")
else
    TABLE_COUNT_AFTER=$(mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -sN -e "SELECT COUNT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA='$DB_NAME'")
fi

if [ "$TABLE_COUNT_AFTER" -gt "0" ]; then
    echo "✓ 数据库验证成功，共创建 $TABLE_COUNT_AFTER 个表" | tee -a "$LOG_FILE"
else
    echo "× 警告: 数据库初始化后未检测到表" | tee -a "$LOG_FILE"
fi

# 配置Nginx
echo "===== 步骤7: 配置Nginx ====="

# 自动检测 mime.types 路径
if [ -f "/etc/nginx/mime.types" ]; then
    MIME_PATH="/etc/nginx/mime.types"
elif [ -f "/www/server/nginx/conf/mime.types" ]; then
    MIME_PATH="/www/server/nginx/conf/mime.types"
else
    echo "× 错误: 未找到 mime.types 文件，请手动指定路径"
    exit 1
fi

# 确定Nginx配置目录
echo "检测Nginx配置环境..."
# 检测宝塔面板
BT_PANEL=0
if [ -f "/etc/init.d/bt" ] || [ -d "/www/server/panel" ]; then
    echo "检测到宝塔面板环境"
    BT_PANEL=1
fi

if [ $BT_PANEL -eq 1 ] && [ -d "/www/server/panel/vhost/nginx" ]; then
    # BT面板环境
    NGINX_CONF_DIR="/www/server/panel/vhost/nginx"
    echo "使用宝塔面板Nginx配置目录: $NGINX_CONF_DIR"
    
    # 检查是否存在网站配置文件
    BT_SITE_NAME="messages"
    if [ -f "$NGINX_CONF_DIR/${BT_SITE_NAME}.conf" ]; then
        echo "发现宝塔面板已有网站配置: ${BT_SITE_NAME}.conf"
        echo "是否覆盖此配置？[y/N]: "
        read -r OVERWRITE
        if [ "$OVERWRITE" != "y" ] && [ "$OVERWRITE" != "Y" ]; then
            echo "保留现有配置，跳过Nginx配置"
            NGINX_CONF_DIR=""
        else
            echo "将覆盖现有配置..."
            # 使用原配置文件名
            NGINX_CONF_FILE="$NGINX_CONF_DIR/${BT_SITE_NAME}.conf"
        fi
    else
        # 使用前端配置文件名
        NGINX_CONF_FILE="$NGINX_CONF_DIR/fish-messages.conf"
    fi
elif [ -d "/etc/nginx/conf.d" ]; then
    # 标准nginx环境
    NGINX_CONF_DIR="/etc/nginx/conf.d"
    NGINX_CONF_FILE="$NGINX_CONF_DIR/fish-messages.conf"
    echo "使用标准Nginx配置目录: $NGINX_CONF_DIR"
else
    echo "× 警告: 未找到Nginx配置目录，跳过Nginx配置"
    echo "请手动配置Nginx"
    NGINX_CONF_DIR=""
fi

# 获取服务器IP地址
# 优先获取公网IP
SERVER_IP=$(curl -s ifconfig.me 2>/dev/null || wget -qO- ifconfig.me 2>/dev/null || curl -s ip.sb 2>/dev/null || curl -s cip.cc 2>/dev/null | head -n1 | cut -d':' -f2 | tr -d ' ')
if [ -z "$SERVER_IP" ]; then
    # 如果公网IP获取失败，尝试获取本地IP
    SERVER_IP=$(ip -4 addr show scope global | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -n 1)
fi
if [ -z "$SERVER_IP" ]; then
    # 如果都失败了，使用默认IP
    SERVER_IP="118.178.183.91"
fi

if [ -n "$NGINX_CONF_DIR" ]; then
    echo "使用Nginx配置目录: $NGINX_CONF_DIR"
    echo "将创建独立配置文件: $NGINX_CONF_FILE"
    
    # 备份原始配置（如果存在）
    if [ -f "$NGINX_CONF_FILE" ]; then
        ORIGINAL_NGINX_CONFIG="${BACKUP_DIR}/$(basename $NGINX_CONF_FILE).bak"
        cp "$NGINX_CONF_FILE" "$ORIGINAL_NGINX_CONFIG"
    fi
    
    # 设置前端端口，默认为80
    FRONTEND_PORT=80
    
    cat > "$NGINX_CONF_FILE" << EOF
server {
    listen 80;
    server_name $SERVER_IP;
    index index.html;
    root $FRONTEND_DIR;
    
    include $MIME_PATH;
    default_type application/octet-stream;
    
    # API代理
    location ^~ /api/ {
        proxy_pass http://127.0.0.1:4577;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    }
    
    # WebSocket配置
    location ^~ /admin/pageview {
        proxy_pass http://127.0.0.1:4577;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_read_timeout 600s;
    }
    
    location / {
        try_files \$uri \$uri/ /index.html;
    }
}
EOF

    # 替换SERVER_IP和FRONTEND_DIR变量
    sed -i "s|\$SERVER_IP|$SERVER_IP|g" "$NGINX_CONF_FILE"
    sed -i "s|\$FRONTEND_DIR|$FRONTEND_DIR|g" "$NGINX_CONF_FILE"

    echo "✓ Nginx配置已创建: $NGINX_CONF_FILE"
    record_file "$NGINX_CONF_FILE"
    NGINX_CONFIGURED=true
    
    # 测试配置并重新加载
    if nginx -t; then
        echo "Nginx配置测试通过，正在重启..."
        # 检查宝塔面板环境下的重启方式
        if [ $BT_PANEL -eq 1 ] && [ -f "/etc/init.d/nginx" ]; then
            echo "使用宝塔面板方式重启Nginx..."
            /etc/init.d/nginx reload
        else
            echo "使用systemctl重启Nginx..."
            systemctl restart nginx
        fi
        echo "✓ Nginx已重启"
        echo "✓ 已使用独立配置文件，未修改全局Nginx设置"
        
        # 如果是宝塔面板，提供额外信息
        if [ $BT_PANEL -eq 1 ]; then
            echo "提示: 在宝塔面板中可通过以下方式访问网站配置:"
            echo "1. 宝塔面板 > 网站 > 找到对应站点 > 设置"
            echo "2. 宝塔面板 > 网站 > 找到对应站点 > 配置文件"
        fi
    else
        echo "× 警告: Nginx配置测试失败，请手动检查配置"
        
        # 宝塔面板环境下提供额外的检查建议
        if [ $BT_PANEL -eq 1 ]; then
            echo "提示: 在宝塔面板中，可通过面板界面检查Nginx配置和错误"
            echo "路径: 宝塔面板 > 网站 > 配置文件 或 宝塔面板 > 网站 > 伪静态"
        fi
    fi
fi

BACKEND_JAR="/www/wwwroot/messages/background/cross-border-commerce-1.0-SNAPSHOT.jar"
CONFIG_DIR="/www/wwwroot/messages/background/config"
CONFIG_FILE="${CONFIG_DIR}/application.yml"
PASSWORD_FILE="/root/mysql_root_password.txt"

if [ -f "$BACKEND_JAR" ]; then
    echo "✅ 检测到后端 JAR 包，准备启动配置..."

    # 1. 创建配置目录
    mkdir -p "$CONFIG_DIR"

    # 2. 获取MySQL密码
    if [ -f "$PASSWORD_FILE" ]; then
        MYSQL_PASSWORD=$(< "$PASSWORD_FILE")
        echo "✓ 从密码文件中获取 MySQL root 密码"
    else
        echo "× 错误: 未找到MySQL密码文件: $PASSWORD_FILE"
        exit 1
    fi

    # 3. 写入 application.yml
    cat > "$CONFIG_FILE" << EOF
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/fish?useSSL=false&serverTimezone=UTC
    username: root
    password: ${MYSQL_PASSWORD}
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL57Dialect
server:
  port: 4577
EOF

    # 4. 设置权限
    chmod 600 "$CONFIG_FILE"
    echo "✅ application.yml 已创建：$CONFIG_FILE"
else
    echo "× 错误: 未找到后端 JAR 包: $BACKEND_JAR"
    exit 1
fi


    # 4. 修改服务配置，指定配置文件位置
    cat > /etc/systemd/system/fish-backend.service << EOF
[Unit]
Description=Fish Backend Service
After=network.target

[Service]
User=root
WorkingDirectory=/www/wwwroot/messages/background
ExecStart=/usr/bin/java -jar cross-border-commerce-1.0-SNAPSHOT.jar --spring.config.location=file:./config/application.yml
Restart=always

[Install]
WantedBy=multi-user.target
EOF

    # 5. 重新加载并重启服务
    systemctl daemon-reload
    systemctl restart fish-backend
    SERVICE_STARTED=true

    echo "✓ 后端服务配置已创建: /etc/systemd/system/fish-backend.service"
    record_file "/etc/systemd/system/fish-backend.service"
    echo "重新加载systemd配置..."
    systemctl daemon-reload
    echo "启动后端服务..."
    systemctl enable fish-backend.service
    check_result "启用后端服务失败"
    systemctl start fish-backend.service
    check_result "启动后端服务失败"
    echo "✓ 后端服务已启动"
else
    echo "× 警告: 未找到后端JAR文件 $BACKEND_JAR，请确保文件存在"
fi


# 配置文件权限
echo "===== 步骤9: 配置应用文件权限 ====="
chmod -R 755 $APP_DIR
echo "✓ 应用文件权限已设置"

# 在部署完成后下载更新脚本
echo -e "${YELLOW}正在下载更新脚本...${NC}"
download_update_script

# 显示部署结果
echo -e "\n${GREEN}部署完成！${NC}"
echo -e "\n${YELLOW}应用环境配置：${NC}"
echo -e "前端目录: $FRONTEND_DIR"
echo -e "后端目录: $BACKEND_DIR"
echo -e "更新脚本: $(dirname "$(readlink -f "$0")")/update.sh"

echo -e "\n${YELLOW}访问信息：${NC}"
echo -e "前端地址: http://$SERVER_IP/"

echo "===== 账号信息 ====="
echo "用户名: root"
echo "密码: Guan@1026"

echo -e "\n${YELLOW}服务状态：${NC}"
echo -e "Nginx: $(systemctl is-active nginx)"
echo -e "MySQL: $(systemctl is-active mysqld)"
echo -e "后端服务: $(systemctl is-active fish-backend)"

echo -e "\n${YELLOW}更新操作：${NC}"
echo -e "如需更新系统，请运行: bash $(dirname "$(readlink -f "$0")")/update.sh"

# 启动前端服务（如有）
# 这里可根据实际情况添加前端服务启动命令
# 检查服务器安全组端口
echo "===== 检查服务器安全组端口 ====="
check_security_group_ports() {
    local ports=(4577 3000)
    local failed=0
    
    for port in "${ports[@]}"; do
        echo "正在检测端口 $port 是否开放..."
        if curl -s -m 5 "http://$SERVER_IP:$port" > /dev/null || nc -z -w 5 "$SERVER_IP" "$port" > /dev/null 2>&1; then
            echo "✓ 端口 $port 已开放"
        else
            echo "× 警告: 端口 $port 未开放"
            echo "请检查服务器安全组设置，确保以下端口已开放："
            echo "- 端口 4577: 后端服务端口"
            echo "- 端口 3000: 前端服务端口"
            failed=1
        fi
    done
    
    if [ $failed -eq 1 ]; then
        echo "请按以下步骤操作："
        echo "1. 登录服务器控制台"
        echo "2. 找到安全组设置"
        echo "3. 添加入站规则，开放端口 4577 和 3000"
        echo "4. 保存设置后重新运行此脚本"
        exit 1
    fi
}
# 检查服务器安全组端口（移动到服务启动后）
check_security_group_ports


# 检查是否需要执行回滚
if [ "$1" = "--rollback" ]; then
    echo "正在执行手动回滚..."
    rollback "用户请求回滚"
fi
