#!/bin/bash
set -euo pipefail

# =========================
# 基本变量
# =========================
FLYWAY_VERSION="11.17.0"
FLYWAY_HOME="/opt/flyway"
MYSQL_USER="root"
MYSQL_PASSWORD_FILE="/root/mysql_root_password.txt"
MYSQL_PASSWORD="$(cat "$MYSQL_PASSWORD_FILE")"
DB_NAME="fish"
SQL_DIR="/www/wwwroot/messages/sql"
SQL_BASE_URL="http://wildrabbitfishplatform.online:8082/sql"

# =========================
# 准备工具与目录
# =========================
command -v wget >/dev/null 2>&1 || { echo "缺少 wget，正在安装..."; (command -v yum >/dev/null && yum install -y wget) || (command -v apt-get >/dev/null && apt-get update && apt-get install -y wget); }
command -v tar  >/dev/null 2>&1 || { echo "缺少 tar，正在安装...";  (command -v yum >/dev/null && yum install -y tar)  || (command -v apt-get >/dev/null && apt-get update && apt-get install -y tar); }

mkdir -p /opt
mkdir -p "$(dirname "$SQL_DIR")"

# =========================
# 下载并解压 Flyway
# =========================
echo "下载 Flyway $FLYWAY_VERSION..."
cd /opt
if [ ! -f "flyway-commandline-${FLYWAY_VERSION}-linux-x64.tar.gz" ]; then
  wget -q "https://github.com/flyway/flyway/releases/download/flyway-${FLYWAY_VERSION}/flyway-commandline-${FLYWAY_VERSION}-linux-x64.tar.gz"
fi

echo "解压 Flyway..."
tar -xzf "flyway-commandline-${FLYWAY_VERSION}-linux-x64.tar.gz"
rm -rf "${FLYWAY_HOME}"
mv "flyway-${FLYWAY_VERSION}" "${FLYWAY_HOME}"

# =========================
# 环境变量
# =========================
echo "设置环境变量..."
if ! grep -q "FLYWAY_HOME=${FLYWAY_HOME}" ~/.bash_profile 2>/dev/null; then
  echo "export FLYWAY_HOME=${FLYWAY_HOME}" >> ~/.bash_profile
  echo 'export PATH=$PATH:$FLYWAY_HOME'   >> ~/.bash_profile
fi
export FLYWAY_HOME=${FLYWAY_HOME}
export PATH=$PATH:$FLYWAY_HOME

# =========================
# 写入 Flyway 配置
# =========================
echo "创建 Flyway 配置文件..."
mkdir -p "${FLYWAY_HOME}/conf"
cat > "${FLYWAY_HOME}/conf/flyway.conf" <<EOF
flyway.url=jdbc:mysql://localhost:3306/${DB_NAME}
flyway.user=${MYSQL_USER}
flyway.password=${MYSQL_PASSWORD}
flyway.locations=filesystem:${SQL_DIR}
flyway.table=flyway_schema_history
flyway.target=latest
# 如目标库已有表但未建过历史表，首次迁移自动基线
flyway.baselineOnMigrate=true
EOF

# =========================
# 创建软链接
# =========================
echo "创建 Flyway 的软链接..."
ln -sf "${FLYWAY_HOME}/flyway" /usr/local/bin/flyway

# =========================
# 初始化：创建 SQL 目录
# =========================
echo "初始化：创建 SQL 目录..."
mkdir -p "${SQL_DIR}"

# =========================
# 下载 SQL 脚本到 ${SQL_DIR}
# =========================
echo "从 ${SQL_BASE_URL} 下载 SQL 脚本到 ${SQL_DIR} ..."

# 优先尝试镜像目录抓取（需要服务器允许目录索引）
# 仅拉取常见命名的迁移脚本（V/R/B 前缀及 .sql）
if ! wget -q -r -np -nH --cut-dirs=0 -A "V*.sql,R*.sql,B*.sql,*.sql" \
     -P "${SQL_DIR}" "${SQL_BASE_URL}/"; then
  echo "目录抓取失败或未开启索引，尝试下载常用文件名..."
fi

# 兜底：尝试若干常用文件名（存在则覆盖）
for f in update.sql latest.sql schema.sql init.sql; do
  wget -q -O "${SQL_DIR}/${f}" "${SQL_BASE_URL}/${f}" 2>/dev/null || true
done

# 简单校验是否至少有一个 .sql
if ! ls "${SQL_DIR}"/*.sql >/dev/null 2>&1; then
  echo "未在 ${SQL_BASE_URL} 找到任何 .sql 脚本，仍将执行 flyway info 以验证连接。"
fi

# =========================
# 验证并迁移
# =========================
echo "验证 Flyway 配置..."
flyway info || true

echo "Flyway初始化"
flyway baseline

echo "执行数据库迁移..."
flyway migrate

echo "Flyway 配置和数据库迁移完成!"
