#!/bin/bash
# Eric · 凉城
# MySQL 一键安装脚本 241203

# 确保脚本以 root 用户运行
if [ "$(id -u)" -ne 0 ]; then
  echo "此脚本需要以 root 用户运行。"
  exit 1
fi

# 更新系统并安装依赖包
echo "安装依赖包..."
apt update && apt install -y wget libaio1 numactl xz-utils

# 检查 MySQL 文件是否已经下载
MYSQL_TAR_FILE="/usr/local/mysql-8.4.3-linux-glibc2.28-aarch64.tar.xz"
if [ ! -f "$MYSQL_TAR_FILE" ]; then
    echo "MySQL 文件不存在，开始下载 MySQL..."
    cd /usr/local
    wget https://dev.mysql.com/get/Downloads/MySQL-8.4/mysql-8.4.3-linux-glibc2.28-aarch64.tar.xz
else
    echo "MySQL 文件已存在，跳过下载..."
fi

# 解压 MySQL
echo "解压 MySQL..."
cd /usr/local
tar xJvf mysql-8.4.3-linux-glibc2.28-aarch64.tar.xz
mv mysql-8.4.3-linux-glibc2.28-aarch64 mysql

# 创建 MySQL 配置文件
echo "创建 MySQL 配置文件..."
cat <<EOF > /etc/my.cnf
[client]
port = 3306
socket = /tmp/mysql.sock

[mysqld]
user = root
basedir = /usr/local/mysql
datadir = /usr/local/mysql/data
port = 3306
bind-address = 127.0.0.1
socket = /tmp/mysql.sock
log-error = /usr/local/mysql/data/mysql-error.log
pid-file = /usr/local/mysql/data/mysql.pid
EOF

# 初始化 MySQL
echo "初始化 MySQL..."
cd /usr/local/mysql
mkdir -p /usr/local/mysql/data
bin/mysqld --initialize --user=root --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data

# 提取临时密码
TEMP_PASSWORD=$(grep 'temporary password' /usr/local/mysql/data/mysql-error.log | awk '{print $NF}')

# 设置权限
echo "设置数据目录和日志目录的权限..."
chown -R root:root /usr/local/mysql
chmod -R 755 /usr/local/mysql

# 将 MySQL 启动脚本复制到 /etc/init.d/
echo "将 MySQL 启动脚本复制到 /etc/init.d/..."
cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysql

# 设置启动脚本权限
echo "设置启动脚本权限..."
chmod +x /etc/init.d/mysql

# MySQL开机自启
touch /etc/rc.local
echo 'service mysql start' >> /etc/rc.local
chmod +x /etc/rc.local

# 启动 MySQL 服务
echo "启动 MySQL 服务..."
/etc/init.d/mysql start
if [ $? -ne 0 ]; then
    echo "启动 MySQL 服务失败，退出脚本..."
    exit 1
fi

# 等待 MySQL 启动完成
sleep 5

# 提示用户输入新密码
echo "请输入新的 MySQL root 密码："
read -s NEW_PASSWORD

# 使用临时密码登录并修改密码
echo "修改 MySQL root 密码..."
/usr/local/mysql/bin/mysql -u root -p"${TEMP_PASSWORD}" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '${NEW_PASSWORD}';"

# 尝试使用新密码登录 MySQL 来验证修改是否成功
echo "尝试使用新密码登录 MySQL..."
/usr/local/mysql/bin/mysql -u root -p"${NEW_PASSWORD}" -e "SHOW DATABASES;"

if [ $? -eq 0 ]; then
    echo "export PATH=/usr/local/mysql/bin:$PATH" >> ~/.bashrc
    rm /usr/local/mysql-8.4.3-linux-glibc2.28-aarch64.tar.xz
    echo "密码修改成功！请手动运行 'source ~/.bashrc' 以使 PATH 设置生效。"
else
    echo "密码修改失败！"
fi
