#!/bin/bash
###############################################################
# discripton:离线一键安装mysql，修改root密码为123456，开启远程访问
# date:2019-12-17
# author:frogchou
# email:frogchou@63.com
###############################################################

echo "用于离线安装mysql数据库，确保数据库安装包和本脚本在同一个目录。"
echo "目前可以安装mysql 5.6 5.7 版本"
read -p "按任意键开始....."

echo “准备安装，检查当前目录是否有mysql安装包......”

# 安装必要软件
yum install -y autoconf wget

#关闭selinux
setenforce 0
sed -i "s%SELINUX=.*%SELINUX=disabled%g" /etc/selinux/config
echo "SELinux 已经关闭"


cur_dir=$(pwd)
arr=( )
count=0
for i in `ls *mysql*.tar.gz`;
	do
	arr[$count]=$i
	let count++
	done

echo "count:"$count
showarr(){
	echo "选择安装包对应的数字："
	for ((i=0;i<${#arr[*]};i++));
	do
	echo " "  $i " " ${arr[i]}
	done
	read -p "请选择：" var
	if [ ! -z "${arr[$var]}" ];then
		#echo “${arr[$var]}”
		installmysql ${arr[$var]}
	else
		echo "!!!!!!选择错误，请重新选择!!!!!!!"
		showarr
	fi
}


removemysql(){
service mysql stop
pkill mysql

yum remove -y mysql mysql-server mysql-libs compat-mysql51

rm -rf /var/lib/mysql
rm -rf /usr/local/mysql
rm -rf /etc/my.cnf
chkconfig --del mysql
userdel -r mysql
groupdel mysql


}



installmysql(){
	removemysql
	mkdir -p /usr/local/mysql
	mysql_path=/usr/local/mysql
	tar zxvf $cur_dir/$1 -C /tmp/
	mysql_install_db_path=( )
	for i in `find /tmp/ -name mysql_install_db`;
		do 
		mysql_install_db_path[0]=$i
		done 
	tmp_path=`dirname $(dirname ${mysql_install_db_path[0]})`
	\cp -r $tmp_path/* $mysql_path/
	
	echo “创建用户”
	groupadd mysql
	useradd -r -g mysql -s /bin/false mysql

	$mysql_path/scripts/mysql_install_db --user=mysql --basedir=$mysql_path --datadir=$mysql_path/data
	rm -rf /etc/init.d/mysql
	\cp $mysql_path/support-files/mysql.server /etc/init.d/mysql

	echo "修改配置文件"
	sed -i '$a basedir=/usr/local/mysql'	$mysql_path/my.cnf
	sed -i '$a datadir=/usr/local/mysql/data' $mysql_path/my.cnf
	sed -i '$a character-set-server=utf8' $mysql_path/my.cnf
	sed -i '$a lower_case_table_name=1' $mysql_path/my.cnf
	\cp $mysql_path/my.cnf /etc/my.cnf
	
	echo "自启动"
	chmod +x /etc/init.d/mysql
	chkconfig --add mysql
	service mysql start
	
	echo "修改root密码为123456"
	$mysql_path/bin/mysqladmin -u root password '123456'
	
	echo "设置远程访问"
	$mysql_path/bin/mysql -u 'root' '-p123456' 'mysql' << eof
GRANT all PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '123456';
FLUSH PRIVILEGES;
eof
	echo "添加环境变量"
	if [ -z "`grep MYSQL_HOME /etc/profile`" ];then
		sed -i '$a export MYSQL_HOME=/usr/local/mysql' /etc/profile
		sed -i '$a export PATH=$PATH:$MYSQL_HOME/bin' /etc/profile
		source /etc/profile
	fi

	echo "重启mysql"
	service mysql restart	
}


if [ ${#arr[*]} -gt 1 ];then
	echo "似乎有多个mysql安装包，选择一个："
	showarr
elif [ ${#arr[*]} -eq 1 ];then
	echo "发现一个mysql安装包，准备安装。"
	installmysql ${arr[0]}
else
	echo "没有发现mysql安装包！！！"
fi

