#!/bin/bash

echo "====================================================="
echo "校园思政新闻平台数据库初始化脚本"
echo "====================================================="
echo ""

# 设置默认值
MYSQL_HOST="localhost"
MYSQL_PORT="3306"
MYSQL_USER="root"
MYSQL_PASSWORD="123456"

# 读取用户输入
read -p "MySQL主机地址 [默认: localhost]: " input_host
MYSQL_HOST=${input_host:-$MYSQL_HOST}

read -p "MySQL端口 [默认: 3306]: " input_port
MYSQL_PORT=${input_port:-$MYSQL_PORT}

read -p "MySQL用户名 [默认: root]: " input_user
MYSQL_USER=${input_user:-$MYSQL_USER}

read -sp "MySQL密码[默认: 123456]: " input_password
MYSQL_PASSWORD=${input_password:-$MYSQL_PASSWORD}
echo ""

# 切换到sql目录
cd sql || exit 1

# 定义执行SQL的函数
execute_sql() {
    local file=$1
    local description=$2
    
    echo "[$description]"
    
    if [ -z "$MYSQL_PASSWORD" ]; then
        mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" < "$file"
    else
        mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" < "$file"
    fi
    
    if [ $? -ne 0 ]; then
        echo "错误: $description 失败！"
        exit 1
    fi
}

# 执行SQL文件
execute_sql "createDB.sql" "1/9 创建数据库"
execute_sql "createTableUser.sql" "2/9 创建用户相关表"
execute_sql "createTablePermission.sql" "3/9 创建权限相关表"
execute_sql "createTableResource.sql" "4/9 创建资源管理相关表"
execute_sql "createTableCourse.sql" "5/9 创建课程管理相关表"
execute_sql "createTableLearning.sql" "6/9 创建学习管理相关表"
execute_sql "createTableUserCenter.sql" "7/9 创建个人中心相关表"
execute_sql "createTableAI.sql" "8/9 创建智能体相关表"
execute_sql "createTableSystem.sql" "9/9 创建系统配置和日志相关表"

cd ..

echo ""
echo "====================================================="
echo "数据库初始化完成！"
echo "====================================================="
echo "数据库名: school_news"
echo "默认用户: admin"
echo "默认密码: 详见 createTableUser.sql"
echo "====================================================="
echo ""

