#!/bin/bash
Stack=$1
if [ "${Stack}" = "" ]; then
    Stack="new"
else
    Stack=$1
fi

mysql_transfer()
{
Old_path="/www/server"
if [ -d /www/server/mysql ]; then
	if [ -d /www/server/data ]; then
	read -p "Enter a new database path (for example, /home/mysql):" Route
		if [ "${Route}" == "" ]; then
		echo "New database path cannot be empty!"
		else
		killall -TERM mysqld
		mkdir ${Route} 1>/dev/null 2>&1
		chown -R root:mysql ${Route}
		echo "Moving the MySQL file, you may need a minute!"
		cp -r -p $Old_path/mysql/* ${Route}
		mkdir ${Route}/var
		echo "Transferring the database file, you may need a minute!"
		cp -r -p $Old_path/data/* ${Route}/var
		chown -R mysql:mysql ${Route}/var
		mv $Old_path/mysql $Old_path/mysql.old
		mv $Old_path/data $Old_path/data.old
		cp /etc/my.cnf /etc/my.cnfold
		cp /etc/init.d/mysqld /etc/init.d/mysqld.old
		#/etc/my/cnf
		sed -i 's#^datadir = '$Old_path/data'#datadir = '${Route}/var'#g' /etc/my.cnf
		sed -i 's#^innodb_data_home_dir = '$Old_path/data'#datadir = '${Route}/var'#g' /etc/my.cnf
		sed -i 's#^innodb_log_group_home_dir = '$Old_path/data'#datadir = '${Route}/var'#g' /etc/my.cnf
		#/etc/init.d/mysqld
		sed -i 's#^  basedir='$Old_path/mysql'#  basedir='${Route}'#g' /etc/init.d/mysqld
		sed -i 's#^  bindir='$Old_path/mysql/bin'#  bindir='${Route}/bin'#g' /etc/init.d/mysqld
		sed -i 's#^    datadir='$Old_path/mysql/data'#    datadir='${Route}/data'#g' /etc/init.d/mysqld
		sed -i 's#^  sbindir='$Old_path/mysql/bin'#  sbindir='${Route}/bin'#g' /etc/init.d/mysqld
		sed -i 's#^  libexecdir='$Old_path/mysql/bin'#  libexecdir='${Route}/bin'#g' /etc/init.d/mysqld
		service mysqld start
			if [ "$?" -eq "0" ]; then
			echo "#####################################"
			echo "Database directory changed successfully!"
			echo "Now MySQL installation path:${Route}"
			echo "New database file path:${Route}/var"
			echo "For more information visit: http://www.tieww.com"
			echo "#####################################"
			else
			echo "#####################################"
			echo "Database directory changes not successful!"
			echo "#####################################"
			fi
		fi
	else
	echo "Sorry, I can't find the /www/server/data directory!"
	fi
else
echo "Sorry, I can't find the /www/server/mysql directory!"
fi
}

Old_mysql()
{
killall -TERM mysqld
rm -rf /etc/my.cnf
mv /etc/my.cnfold /etc/my.cnf
rm -rf /etc/init.d/mysqld
mv /etc/init.d/mysqld.old /etc/init.d/mysqld
mv /www/server/data.old /www/server/data
mv /www/server/mysql.old /www/server/mysql
service mysqld start
if [ "$?" -eq "0" ]; then
echo "Recover successfully!"
echo "For more information visit: http://www.tieww.com"
else
echo "Recovery failure!"
echo "For more information visit: http://www.tieww.com"
fi
}

case "${Stack}" in
    new)
        mysql_transfer
        ;;
    old)
		Old_mysql
        ;;
    *)
       echo "Usage: $0 {new|old}"
        ;;
esac