#!/bin/bash
# ============================================================
# ERP 数据库初始化脚本
# 用法: ./init-db.sh [MySQL Host] [MySQL Port] [Root Password]
# ============================================================

set -e

MYSQL_HOST="${1:-mysql}"
MYSQL_PORT="${2:-3306}"
MYSQL_ROOT_PASSWORD="${3:-root123456}"
ERP_DB="erp_java"
ERP_USER="erp_user"
ERP_PASSWORD="erp123456"

echo "=========================================="
echo "ERP 数据库初始化"
echo "MySQL: $MYSQL_HOST:$MYSQL_PORT"
echo "=========================================="

# 等待MySQL就绪
echo "[1/5] 等待MySQL服务就绪..."
for i in {1..30}; do
  if mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -uroot -p"$MYSQL_ROOT_PASSWORD" -e "SELECT 1" &>/dev/null; then
    echo "MySQL已就绪"
    break
  fi
  echo "等待MySQL... ($i/30)"
  sleep 2
done

# 创建数据库
echo "[2/5] 创建数据库..."
mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -uroot -p"$MYSQL_ROOT_PASSWORD" <<EOF
CREATE DATABASE IF NOT EXISTS ${ERP_DB} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS nacos_config CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS rocketmq CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS seata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
FLUSH PRIVILEGES;
EOF

# 创建应用用户
echo "[3/5] 创建应用用户..."
mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -uroot -p"$MYSQL_ROOT_PASSWORD" <<EOF
CREATE USER IF NOT EXISTS '${ERP_USER}'@'%' IDENTIFIED BY '${ERP_PASSWORD}';
CREATE USER IF NOT EXISTS '${ERP_USER}'@'localhost' IDENTIFIED BY '${ERP_PASSWORD}';
GRANT ALL PRIVILEGES ON ${ERP_DB}.* TO '${ERP_USER}'@'%';
GRANT ALL PRIVILEGES ON ${ERP_DB}.* TO '${ERP_USER}'@'localhost';
GRANT ALL PRIVILEGES ON nacos_config.* TO '${ERP_USER}'@'%';
GRANT ALL PRIVILEGES ON rocketmq.* TO '${ERP_USER}'@'%';
GRANT ALL PRIVILEGES ON seata.* TO '${ERP_USER}'@'%';
FLUSH PRIVILEGES;
EOF

# 执行初始化SQL
echo "[4/5] 执行初始化SQL..."
if [ -f /docker-entrypoint-initdb.d/init.sql ]; then
  mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -uroot -p"$MYSQL_ROOT_PASSWORD" "$ERP_DB" < /docker-entrypoint-initdb.d/init.sql
  echo "init.sql 执行完成"
fi

# 执行Flyway/Liquibase迁移（如果存在）
echo "[5/5] 执行数据库迁移..."
for migration_file in /docker-entrypoint-initdb.d/migration/*.sql; do
  if [ -f "$migration_file" ]; then
    echo "执行迁移: $(basename $migration_file)"
    mysql -h"$MYSQL_HOST" -P"$MYSQL_PORT" -uroot -p"$MYSQL_ROOT_PASSWORD" "$ERP_DB" < "$migration_file"
  fi
done

echo "=========================================="
echo "数据库初始化完成!"
echo "=========================================="
