#!/bin/bash
#该shell为使用mysql二进制包安装mysql-5.6
#测试系统:Centos7
#mysql下载地址 https://dev.mysql.com/downloads/mysql/
#下载一个mysql5.6的二进制包并执行shell
#https://cdn.mysql.com//Downloads/MySQL-5.6/mysql-5.6.41-linux-glibc2.12-x86_64.tar.gz
#shell执行方式:
#sh mysql_install.sh mysql-5.6.41-linux-glibc2.12-x86_64.tar.gz

port=3306
basedir=/opt/mysql
datadir=/data
mysql_passwd=`openssl rand -base64 9`
function install
{
sudo yum -y install autoconf libaio-devel perl-Module-Install.noarch 
sudo mkdir -p $basedir
sudo mkdir -p $datadir
sudo tar -xvf $1 -C $basedir --strip-components 1
sudo useradd -r mysql -s /sbin/nologin
sudo chown -R mysql.mysql $datadir
sudo chown -R mysql.mysql $basedir

sudo $basedir/scripts/mysql_install_db --basedir=$basedir \
--datadir=$datadir --user=mysql --pid-file=$basedir/mysql.pid ||exit -1

sudo cp $basedir/support-files/mysql.server /etc/init.d/mysqld
sudo chmod +x /etc/init.d/mysqld

if [[ ! -f /etc/my.cnf.bk ]]; then
sudo cp /etc/my.cnf /etc/my.cnf.bk
fi

sudo cat>/etc/my.cnf <>/etc/rc.local
sudo chmod +x /etc/rc.local
sudo mysqladmin -u root password "$mysql_passwd"
sudo mysql -uroot -p$mysql_passwd -e "delete from mysql.user where user=''; \
delete from mysql.db where user='';"

sudo echo "port $port" >>$basedir/mysql.txt
sudo echo "basedir $basedir" >>$basedir/mysql.txt
sudo echo "datadir $datadir" >>$basedir/mysql.txt
sudo echo "root passwd:$mysql_passwd" >>$basedir/mysql.txt
sudo echo "mysql初始密码保存在$basedir/mysql.txt"  
}

case $1 in
"")
echo "Example: sh mysql_install.sh [压缩包路径]"
exit 1;;
*)
if test ! -f $1
then
echo "压缩包名称或路径错误!"
else
install
fi
;;
esac