#!/bin/bash

# 确保目标目录存在并有正确的权限
echo "Creating target directory and setting permissions..."
sudo mkdir -p /mnt/hgfs/workspace/viewwatch
sudo chown mysql:mysql /mnt/hgfs/workspace/viewwatch

# 停止 MySQL 服务
echo "Stopping MySQL service..."
sudo systemctl stop mysqld

# 复制数据库文件到新位置
echo "Copying database files to new location..."
sudo cp -R /usr/local/mysql/data/viewwatch /mnt/hgfs/workspace/

# 备份原始 viewwatch 目录（以防万一）
echo "Backing up original viewwatch directory..."
sudo mv /usr/local/mysql/data/viewwatch /usr/local/mysql/data/viewwatch_backup

# 创建一个软链接，将新位置链接到原来的位置
echo "Creating symbolic link..."
sudo ln -s /mnt/hgfs/workspace/viewwatch /usr/local/mysql/data/viewwatch

# 调整权限
echo "Adjusting permissions..."
sudo chown -R mysql:mysql /mnt/hgfs/workspace/viewwatch
sudo chmod -R 700 /mnt/hgfs/workspace/viewwatch

# 重启 MySQL 服务
echo "Restarting MySQL service..."
sudo systemctl start mysqld

# 等待几秒钟让 MySQL 完全启动
sleep 10

# 检查 MySQL 状态
echo "Checking MySQL status after restart..."
sudo systemctl status mysqld

if [ $? -ne 0 ]; then
    echo "Failed to start MySQL after restart. Reverting changes..."
    sudo rm -f /usr/local/mysql/data/viewwatch
    sudo mv /usr/local/mysql/data/viewwatch_backup /usr/local/mysql/data/viewwatch
    sudo systemctl start mysqld
    echo "Changes reverted. Please check MySQL logs for more information."
    exit 1
fi

echo "MySQL is running. Database migration completed."

# 如果一切正常，删除备份
echo "Removing backup..."
sudo rm -rf /usr/local/mysql/data/viewwatch_backup

echo "Database migration script execution completed."
