#!/bin/bash

echo "开始初始化旅游内容创作系统数据库..."

# 检查MySQL是否安装
if ! command -v mysql &> /dev/null; then
    echo "错误: MySQL未安装，请先安装MySQL"
    exit 1
fi

# 询问MySQL root密码
read -sp "请输入MySQL root密码（如果没有设置请直接回车）: " MYSQL_ROOT_PASSWORD
echo ""

# 创建环境变量配置文件
cat > .env.db <<EOF
# 数据库环境变量配置
DB_HOST=localhost
DB_USER=travel_user
DB_PASSWORD=travel123
DB_NAME=travel_content
DB_PORT=3306
EOF

echo "已创建环境变量配置文件 .env.db"
echo "可以通过以下命令加载环境变量:"
echo "source .env.db"

# 自动加载环境变量
source .env.db
echo "已自动加载环境变量"

# 根据是否有密码使用不同的命令执行SQL脚本
echo "执行SQL脚本创建数据库和表..."
if [ -z "$MYSQL_ROOT_PASSWORD" ]; then
    # 无密码
    mysql -u root <<EOF
-- 创建数据库
CREATE DATABASE IF NOT EXISTS travel_content DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建用户并授权
CREATE USER IF NOT EXISTS 'travel_user'@'localhost' IDENTIFIED BY 'travel123';
GRANT ALL PRIVILEGES ON travel_content.* TO 'travel_user'@'localhost';
GRANT ALL PRIVILEGES ON travel_content.* TO 'root'@'localhost';

-- 刷新权限
FLUSH PRIVILEGES;

-- 使用数据库
USE travel_content;

-- 执行完整的SQL脚本
source db/init_database.sql;
EOF
else
    # 有密码
    mysql -u root -p"$MYSQL_ROOT_PASSWORD" <<EOF
-- 创建数据库
CREATE DATABASE IF NOT EXISTS travel_content DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建用户并授权
CREATE USER IF NOT EXISTS 'travel_user'@'localhost' IDENTIFIED BY 'travel123';
GRANT ALL PRIVILEGES ON travel_content.* TO 'travel_user'@'localhost';
GRANT ALL PRIVILEGES ON travel_content.* TO 'root'@'localhost';

-- 刷新权限
FLUSH PRIVILEGES;

-- 使用数据库
USE travel_content;

-- 执行完整的SQL脚本
source db/init_database.sql;
EOF
fi

# 检查执行结果
if [ $? -eq 0 ]; then
    echo "数据库初始化成功！"
    echo "数据库名称: travel_content"
    echo "用户: travel_user (密码: travel123)"
    
    # 显示表信息
    echo "已创建表:"
    mysql -u travel_user -ptravel123 -e "USE travel_content; SHOW TABLES;"
    
    # 更新配置文件
    cat > config/database.json <<EOF
{
    "host": "\${DB_HOST:-localhost}",
    "user": "\${DB_USER:-travel_user}",
    "password": "\${DB_PASSWORD:-travel123}",
    "database": "\${DB_NAME:-travel_content}",
    "port": "\${DB_PORT:-3306}",
    "charset": "utf8mb4"
}
EOF
    echo "已更新数据库配置文件"
else
    echo "数据库初始化失败，请检查错误信息"
fi

echo "初始化完成" 