#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# Check if user is root
if [ $(id -u) != "0" ]; then
    echo "Error: You must be root to run this script, please use root to install BBR"
    exit 0
fi

clear
echo "+------------------------------------------------------------------------+"
echo "|                          GooGle TCP BBR                                |"
echo "+------------------------------------------------------------------------+"
echo "|        A tool to auto-compile & install BBR on CentOS                  |"
echo "+------------------------------------------------------------------------+"
echo "|                 Welcome to  http://github.com/52fancy                  |"
echo "+------------------------------------------------------------------------+"

Get_RHEL_Version()
{
    if grep -Eqi "release 5." /etc/redhat-release; then
        RHEL_Version='5'
    elif grep -Eqi "release 6." /etc/redhat-release; then
        RHEL_Version='6'
    elif grep -Eqi "release 7." /etc/redhat-release; then
        RHEL_Version='7'
    fi
}

Get_RHEL_Version
if [ $RHEL_Version != "6" ]; then
    echo "Error: You must be CentOS 6 to run this script, please use CentOS 6 to install BBR"
	exit 0
fi

Get_OS_Bit()
{
    if [[ `getconf WORD_BIT` = '32' && `getconf LONG_BIT` = '64' ]] ; then
        OS_Bit='64'
    else
        OS_Bit='32'
    fi
}

Install()
{
    Get_OS_Bit
    if uname -r | grep -Eqi "4.9."; then
	    if [ ! `cat /etc/sysctl.conf | grep -i -E "net.core.default_qdisc=fq"` ]; then
		    echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
		fi
		if [ ! `cat /etc/sysctl.conf | grep -i -E "net.ipv4.tcp_congestion_control=bbr"` ]; then
		    echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
		fi
		sysctl -p
		sed -i "/BBR.sh/d" /etc/rc.d/rc.local
		rm -f /tmp/BBR.sh
	else
	    echo -n "内核不一致，即将替换内核 [y or n]:  "
		read code
		if [ $code = "y" -o $code = "Y" ]; then
		    if [ $OS_Bit = "64" ]; then
		        rpm -ivh http://elrepo.org/people/ajb/devel/kernel-ml/el6/x86_64/RPMS/kernel-ml-4.9.0-0.rc8.el6.elrepo.x86_64.rpm --force
			fi
			if [ $OS_Bit = "32" ]; then
		        rpm -ivh http://elrepo.org/people/ajb/devel/kernel-ml/el6/x86_32/RPMS/kernel-ml-4.9.0-0.rc8.el6.elrepo.i686.rpm --force
			fi
			sed -i "s/default=1/default=0/g" /boot/grub/grub.conf
			cp $0 /tmp/BBR.sh
			rm -f $0
			echo "sh /tmp/BBR.sh" >>/etc/rc.d/rc.local
			echo "服务器重启后便是安装成功了！"
			reboot
		fi
		if [ $code = "n" -o $code = "N" ]; then
		    echo "程序即将退出安装"
            exit 0
		fi
	fi
}
 
Install
exit 0
