#!/bin/bash
#当前版本  16.0
#2023-10-30 18点30分

#修改版13.0 mis
#修改nginx-html目录权限（针对模板主机）

#修改版14.0 mis
#增加zabbix脚本自定义mysql数据库名称

#修改版15.0 mis
# 修改开机自启,增加consul的开机自启

#修改版16.0 mis
# 更新openresty版本，从openresty-1.15.8.1.tar.gz更新至2023年7月19日发布版本openresty-1.21.4.2.tar.gz

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

sh_ver="1.2.1"
github="raw.githubusercontent.com/chiakge/Linux-NetSpeed/master"

Green_font_prefix="\033[32m" && Red_font_prefix="\033[31m" && Green_background_prefix="\033[42;37m" && Red_background_prefix="\033[41;37m" && Font_color_suffix="\033[0m"
Info="${Green_font_prefix}[信息]${Font_color_suffix}"
Error="${Red_font_prefix}[错误]${Font_color_suffix}"
Tip="${Green_font_prefix}[注意]${Font_color_suffix}"

#设置rz别名
echo "alias  rz='rz -Ey'" >> /root/.bashrc


#安装宝塔
install_BT(){
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
LANG=en_US.UTF-8
is64bit=`getconf LONG_BIT`

#修改防火墙信任区域
firewall_port=`firewall-cmd --list-all |awk '{print $1}'|awk 'NR==1{print}'`
if [ $firewall_port != public ];then
      firewall-cmd --set-default-zone=public
else
        echo "Firewalls are public areas!"
fi

if  [ ! -x /bin/firewall-cmd ];then
	yum -y install firewalld
	systemctl unmask  firewalld
	systemctl restart firewalld 						  
	firewall-cmd --permanent --zone=public --add-port=20/tcp
	firewall-cmd --permanent --zone=public --add-port=21/tcp
	firewall-cmd --permanent --zone=public --add-port=22/tcp
	firewall-cmd --permanent --zone=public --add-port=80/tcp
	firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp 
	firewall-cmd --permanent --zone=public --add-port=443/tcp
	firewall-cmd --permanent --zone=public --add-port=6868/tcp
	firewall-cmd --permanent --zone=public --add-port=6869/tcp
	firewall-cmd --permanent --zone=public --add-port=8090/tcp
	firewall-cmd --permanent --zone=public --add-port=5555/tcp 
	firewall-cmd --permanent --zone=public --add-port=9000/tcp 
	firewall-cmd --permanent --zone=public --add-port=6868/tcp 
	firewall-cmd --permanent --zone=public --add-port=6869/tcp 
	firewall-cmd --permanent --zone=public --add-port=9010/tcp 
	firewall-cmd --permanent --zone=public --add-port=10050/tcp
	firewall-cmd --permanent --zone=public --add-port=2222/tcp	
	firewall-cmd --permanent --zone=public --add-port=63240/tcp
	firewall-cmd --reload
fi

if [ -f "/usr/bin/apt-get" ];then
	isDebian=`cat /etc/issue|grep Debian`
	if [ "$isDebian" != "" ];then
		wget -O install.sh http://download.bt.cn/install/install-ubuntu_6.0.sh && bash install.sh
		exit;
	else
		wget -O install.sh http://download.bt.cn/install/install-ubuntu_6.0.sh && sudo bash install.sh
		exit;
	fi
fi

if [ "$is64bit" != '64' ];then
	echo "====================================="
	echo "抱歉, 6.0不支持32位系统, 请使用64位系统或安装宝塔5.9!";
	exit 0;
fi

py26=$(python -V 2>&1|grep '2.6.')
if [ "$py26" != "" ];then
	echo "====================================="
	echo "抱歉, 6.0不支持Centos6.x,请安装Centos7或安装宝塔5.9";
	exit 0;
fi

CN='http://125.88.182.172:5880'

Install_Check(){
	while [ "$yes" == 'yes' ] && [ "$yes" != 'n' ]
	do
		echo -e "----------------------------------------------------"
		echo -e "已有Web环境，安装宝塔可能影响现有站点"
		echo -e "Web service is alreday installed,Can't install panel"
		echo -e "----------------------------------------------------"
		read -p "输入yes强制安装/Enter yes to force installation (yes/n): " yes;
	done 
	if [ "$yes" == 'n' ];then
		exit;
	fi
}

Web_Service_Check(){
	if [ -f "/etc/init.d/nginx" ]; then
        nginxV=$(cat /etc/init.d/nginx|grep /www/server/nginx)
        if [ "${nginxV}" = "" ];then
        	Install_Check
        fi
    fi

    if [ -f "/etc/init.d/httpd" ]; then
        httpdV=$(cat /etc/init.d/httpd|grep /www/server/apache)
        if [ "${httpdV}" = "" ];then
        	Install_Check
        fi
    fi

    if [ -f "/etc/init.d/mysqld" ]; then
        mysqlV=$(cat /etc/init.d/mysqld|grep /www/server/mysql)
        if [ "${mysqlV}" = "" ];then
        	Install_Check
        fi
    fi
}

Web_Service_Check

echo "
+----------------------------------------------------------------------
| Bt-WebPanel 6.0 FOR CentOS
+----------------------------------------------------------------------
| Copyright © 2015-2099 BT-SOFT(http://www.bt.cn) All rights reserved.
+----------------------------------------------------------------------
| The WebPanel URL will be http://SERVER_IP:2222 when installed.
+----------------------------------------------------------------------
"
get_node_url(){
	nodes=(http://125.88.182.172:5880 http://103.224.251.67 http://128.1.164.196);
	i=1;
	if [ ! -f /bin/curl ];then
		if [ -f /usr/local/curl/bin/curl ];then
			ln -sf /usr/local/curl/bin/curl /bin/curl
		else
			yum install curl -y
		fi
	fi
	for node in ${nodes[@]};
	do
		start=`date +%s.%N`
		result=`curl -sS --connect-timeout 3 -m 60 $node/check.txt`
		if [ $result = 'True' ];then
			end=`date +%s.%N`
			start_s=`echo $start | cut -d '.' -f 1`
			start_ns=`echo $start | cut -d '.' -f 2`
			end_s=`echo $end | cut -d '.' -f 1`
			end_ns=`echo $end | cut -d '.' -f 2`
			time_micro=$(( (10#$end_s-10#$start_s)*1000000 + (10#$end_ns/1000 - 10#$start_ns/1000) ))
			time_ms=$(($time_micro/1000))
			values[$i]=$time_ms;
			urls[$time_ms]=$node
			i=$(($i+1))
		fi
	done
	j=5000
	for n in ${values[@]};
	do
		if [ $j -gt $n ];then
			j=$n
		fi
	done
	if [ $j = 5000 ];then
		NODE_URL='http://download.bt.cn';
	else
		NODE_URL=${urls[$j]}
	fi
	
}
echo '---------------------------------------------';
echo "Selected download node...";
get_node_url
download_Url=$NODE_URL
echo "Download node: $download_Url";
echo '---------------------------------------------';
setup_path=/www
port='2222'
echo 2222 > /www/server/panel/data/port.pl
if [ -f $setup_path/server/panel/data/port.pl ];then
	port=`cat $setup_path/server/panel/data/port.pl`
fi

while [ "$go" == 'y' ] && [ "$go" != 'n' ]
do
	read -p "Do you want to install Bt-Panel to the $setup_path directory now?(y/n): " go;
done

if [ "$go" == 'n' ];then
	exit;
fi

path=/etc/yum.conf
isExc=`cat $path|grep httpd`
if [ "$isExc" = "" ];then
    echo "exclude=httpd nginx php mysql mairadb python-psutil python2-psutil" >> $path
fi


#数据盘自动分区
fdiskP(){
	
	for i in `cat /proc/partitions|grep -v name|grep -v ram|awk '{print $4}'|grep -v '^$'|grep -v '[0-9]$'|grep -v 'vda'|grep -v 'xvda'|grep -v 'sda'|grep -e 'vd' -e 'sd' -e 'xvd'`;
	do
		#判断指定目录是否被挂载
		isR=`df -P|grep $setup_path`
		if [ "$isR" != "" ];then
			echo "Error: The $setup_path directory has been mounted."
			return;
		fi
		
		isM=`df -P|grep '/dev/${i}1'`
		if [ "$isM" != "" ];then
			echo "/dev/${i}1 has been mounted."
			continue;
		fi
			
		#判断是否存在未分区磁盘
		isP=`fdisk -l /dev/$i |grep -v 'bytes'|grep "$i[1-9]*"`
		if [ "$isP" = "" ];then
				#开始分区
				fdisk -S 56 /dev/$i << EOF
n
p
1


wq
EOF

			sleep 5
			#检查是否分区成功
			checkP=`fdisk -l /dev/$i|grep "/dev/${i}1"`
			if [ "$checkP" != "" ];then
				#格式化分区
				mkfs.ext4 /dev/${i}1
				mkdir $setup_path
				#挂载分区
				sed -i "/\/dev\/${i}1/d" /etc/fstab
				echo "/dev/${i}1    $setup_path    ext4    defaults    0 0" >> /etc/fstab
				mount -a
				df -h
			fi
		else
			#判断是否存在Windows磁盘分区
			isN=`fdisk -l /dev/$i|grep -v 'bytes'|grep -v "NTFS"|grep -v "FAT32"`
			if [ "$isN" = "" ];then
				echo 'Warning: The Windows partition was detected. For your data security, Mount manually.';
				return;
			fi
			
			#挂载已有分区
			checkR=`df -P|grep "/dev/$i"`
			if [ "$checkR" = "" ];then
					mkdir $setup_path
					sed -i "/\/dev\/${i}1/d" /etc/fstab
					echo "/dev/${i}1    $setup_path    ext4    defaults    0 0" >> /etc/fstab
					mount -a
					df -h
			fi
			
			#清理不可写分区
			echo 'True' > $setup_path/checkD.pl
			if [ ! -f $setup_path/checkD.pl ];then
					sed -i "/\/dev\/${i}1/d" /etc/fstab
					mount -a
					df -h
			else
					rm -f $setup_path/checkD.pl
			fi
		fi
	done
}
#fdiskP

#自动挂载Swap
autoSwap()
{
	swap=`free |grep Swap|awk '{print $2}'`
	if [ $swap -gt 1 ];then
        echo "Swap total sizse: $swap";
		return;
	fi
	if [ ! -d /www ];then
		mkdir /www
	fi
	swapFile='/www/swap'
	dd if=/dev/zero of=$swapFile bs=1M count=1025
	mkswap -f $swapFile
    swapon $swapFile
    echo "$swapFile    swap    swap    defaults    0 0" >> /etc/fstab
	swap=`free |grep Swap|awk '{print $2}'`
	if [ $swap -gt 1 ];then
        echo "Swap total sizse: $swap";
		return;
	fi
	
	sed -i "/\/www\/swap/d" /etc/fstab
	rm -f $swapFile
}
autoSwap

#判断kernel-headers组件是否安装
rpm -qa | grep kernel-headers > kernel-headers.pl
kernelStatus=`cat kernel-headers.pl`
#判断华为云
huaweiLogin=`cat /etc/motd |grep 4000-955-988`
huaweiSys=`cat /etc/redhat-release | grep ' 7.'`
if [ "$kernelStatus" = "" ]; then
	if [ "$huaweiLogin" != "" ] && [ "$huaweiSys" != "" ]; then
		wget $download_Url/src/kernel-headers-3.10.0-514.el7.x86_64.rpm
		rpm -ivh kernel-headers-3.10.0-514.el7.x86_64.rpm
		rm -f kernel-headers-3.10.0-514.el7.x86_64.rpm
	else
		yum install kernel-headers -y
	fi
fi
rm -f kernel-headers.pl

yum install ntp -y
rm -rf /etc/localtime
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

echo 'Synchronizing system time...'
ntpdate 0.asia.pool.ntp.org
startTime=`date +%s`
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
for pace in python-devel python-imaging zip unzip openssl openssl-devel gcc libxml2 libxml2-devel libxslt* zlib zlib-devel libjpeg-devel libpng-devel libwebp libwebp-devel freetype freetype-devel lsof pcre pcre-devel vixie-cron crontabs icu libicu-devel c-ares;
do
	yum -y install ${pace}; 
done

if [ -f "/usr/bin/dnf" ]; then
	dnf install -y redhat-rpm-config
fi
yum install python-devel -y

py26=$(python -V 2>&1|grep '2.6.')
if [ "$py26" != "" ];then
	if [ ! -f /etc/yum.repos.d/epel.repo ];then
		wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
	fi
    if [ ! -f /usr/bin/python3 ];then
		yum install python34 python34-devel -y
		if [ ! -f /usr/bin/python3 ];then
			echo "python3.4 install error!"
			exit 0;
		fi
		isSed=$(cat /usr/bin/yum|grep /usr/bin/python2.6)
		if [ "$isSed" == "" ];then
			sed -i "s#/usr/bin/python#/usr/bin/python2.6#" /usr/bin/yum
		fi
		#rm -f /usr/bin/python2
		mv -f /usr/bin/python /usr/bin/python2_backup
		ln -sf /usr/bin/python3 /usr/bin/python
	fi
	if [ ! -f /usr/bin/pip3 ];then
		wget --no-check-certificate https://bootstrap.pypa.io/get-pip.py
		python3 get-pip.py
		mv -f /usr/bin/pip /usr/bin/pip_backup 
		ln -sf /usr/bin/pip3.4 /usr/bin/pip
	fi
fi

tmp=`python -V 2>&1|awk '{print $2}'`
pVersion=${tmp:0:3}

Install_setuptools()
{
	if [ ! -f "/usr/bin/easy_install" ];then
		wget -O setuptools-33.1.1.zip $download_Url/install/src/setuptools-33.1.1.zip -T 10
		unzip setuptools-33.1.1.zip
		rm -f setuptools-33.1.1.zip
		cd setuptools-33.1.1
		python setup.py install
		cd ..
		rm -rf setuptools-33.1.1
	fi
	
	if [ ! -f "/usr/bin/easy_install" ];then
		echo '=================================================';
		echo -e "\033[31msetuptools installation failed. \033[0m";
		exit;
	fi
}

Install_pip()
{
	ispip=`pip -V |grep from`
	if [ "$ispip" == "" ];then
		if [ ! -f "/usr/bin/easy_install" ];then
			Install_setuptools
		fi
		wget -O pip-9.0.1.tar.gz $download_Url/install/src/pip-9.0.1.tar.gz -T 10
		tar xvf pip-9.0.1.tar.gz
		rm -f pip-9.0.1.tar.gz
		cd pip-9.0.1
		python setup.py install
		cd ..
		rm -rf pip-9.0.1
	fi
	ispip=`pip -V |grep from`
	if [ "$ispip" = "" ];then
		echo '=================================================';
		echo -e "\033[31m Python-pip installation failed. \033[0m";
		exit;
	fi
	
	pip install -U pip
}

Install_Pillow()
{
	isSetup=`python -m PIL 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		isFedora = `cat /etc/redhat-release |grep Fedora`
		if [ "$isFedora" != "" ];then
			pip install Pillow
			return;
		fi
		wget -O Pillow-3.2.0.zip $download_Url/install/src/Pillow-3.2.0.zip -T 10
		unzip Pillow-3.2.0.zip
		rm -f Pillow-3.2.0.zip
		cd Pillow-3.2.0
		python setup.py install
		cd ..
		rm -rf Pillow-3.2.0
	fi
	
	isSetup=`python -m PIL 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mPillow installation failed. \033[0m";
		exit;
	fi
}

Install_psutil()
{
	isSetup=`python -m psutil 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O psutil-5.2.2.tar.gz $download_Url/install/src/psutil-5.2.2.tar.gz -T 10
		tar xvf psutil-5.2.2.tar.gz
		rm -f psutil-5.2.2.tar.gz
		cd psutil-5.2.2
		python setup.py install
		cd ..
		rm -rf psutil-5.2.2
	fi
	isSetup=`python -m psutil 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mpsutil installation failed. \033[0m";
		exit;
	fi
}

Install_mysqldb()
{
	isSetup=`python -m MySQLdb 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O MySQL-python-1.2.5.zip $download_Url/install/src/MySQL-python-1.2.5.zip -T 10
		unzip MySQL-python-1.2.5.zip
		rm -f MySQL-python-1.2.5.zip
		cd MySQL-python-1.2.5
		python setup.py install
		cd ..
		rm -rf MySQL-python-1.2.5
	fi
}

Install_chardet()
{
	isSetup=`python -m chardet 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O chardet-2.3.0.tar.gz $download_Url/install/src/chardet-2.3.0.tar.gz -T 10
		tar xvf chardet-2.3.0.tar.gz
		rm -f chardet-2.3.0.tar.gz
		cd chardet-2.3.0
		python setup.py install
		cd ..
		rm -rf chardet-2.3.0
	fi	
	
	isSetup=`python -m chardet 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mchardet installation failed. \033[0m";
		exit;
	fi
}

Install_webpy()
{
	isSetup=`python -m web 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O web.py-0.38.tar.gz $download_Url/install/src/web.py-0.38.tar.gz -T 10
		tar xvf web.py-0.38.tar.gz
		rm -f web.py-0.38.tar.gz
		cd web.py-0.38
		python setup.py install
		cd ..
		rm -rf web.py-0.38
	fi
	
	isSetup=`python -m web 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mweb.py installation failed. \033[0m";
		exit;
	fi
}


Install_setuptools
Install_pip

if [ "${download_Url}" = "$CN" ]; then
	if [ ! -d "/root/.pip" ];then
		mkdir ~/.pip
	fi
    cat > ~/.pip/pip.conf <<EOF
[global]
index-url = https://pypi.doubanio.com/simple/

[install]
trusted-host=pypi.doubanio.com
EOF
fi

isPsutil=`python -m psutil 2>&1|grep package`
if [ "$isPsutil" != "" ];then
	psutil_version=`python -c 'import psutil;print psutil.__version__;' |grep '5.'` 
	if [ "$psutil_version" = '' ];then
		pip uninstall psutil -y 
	fi
fi
yum install libffi-devel -y
pip install --upgrade setuptools
pip install -U pip
pip install itsdangerous==0.24
pip install paramiko==2.0.2
pip install flask-socketio==3.0.2
pip install python-socketio==2.1.2
for p_name in psutil chardet virtualenv Flask Flask-Session Flask-SocketIO flask-sqlalchemy Pillow gunicorn gevent-websocket;
do
	pip install ${p_name}
done

pip install psutil chardet virtualenv Flask Flask-Session Flask-SocketIO flask-sqlalchemy Pillow gunicorn gevent-websocket paramiko
Install_Pillow
Install_psutil

pip install gunicorn

if [  -f /www/server/mysql/bin/mysql ]; then
	pip install mysql-python
	Install_mysqldb
fi
Install_chardet

mkdir -p $setup_path/server/panel/logs
mkdir -p $setup_path/server/panel/vhost/apache
mkdir -p $setup_path/server/panel/vhost/nginx
mkdir -p $setup_path/server/panel/vhost/rewrite


if [ -f '/etc/init.d/bt' ];then
	/etc/init.d/bt stop
fi

mkdir -p /www/server
mkdir -p /www/wwwroot
mkdir -p /www/wwwlogs
mkdir -p /www/backup/database
mkdir -p /www/backup/site

if [ ! -f "/usr/bin/unzip" ];then
	#rm -f /etc/yum.repos.d/epel.repo
	yum install unzip -y
fi
wget -O panel.zip $download_Url/install/src/panel6.zip -T 10
wget -O /etc/init.d/bt $download_Url/install/src/bt6.init -T 10
if [ -f "$setup_path/server/panel/data/default.db" ];then
	if [ -d "/$setup_path/server/panel/old_data" ];then
		rm -rf $setup_path/server/panel/old_data
	fi
	mkdir -p $setup_path/server/panel/old_data
	mv -f $setup_path/server/panel/data/default.db $setup_path/server/panel/old_data/default.db
	mv -f $setup_path/server/panel/data/system.db $setup_path/server/panel/old_data/system.db
	mv -f $setup_path/server/panel/data/port.pl $setup_path/server/panel/old_data/port.pl
	mv -f $setup_path/server/panel/data/admin_path.pl $setup_path/server/panel/old_data/admin_path.pl
fi

unzip -o panel.zip -d $setup_path/server/ > /dev/null

if [ -d "$setup_path/server/panel/old_data" ];then
	mv -f $setup_path/server/panel/old_data/default.db $setup_path/server/panel/data/default.db
	mv -f $setup_path/server/panel/old_data/system.db $setup_path/server/panel/data/system.db
	mv -f $setup_path/server/panel/old_data/port.pl $setup_path/server/panel/data/port.pl
	mv -f $setup_path/server/panel/old_data/admin_path.pl $setup_path/server/panel/data/admin_path.pl
	if [ -d "/$setup_path/server/panel/old_data" ];then
		rm -rf $setup_path/server/panel/old_data
	fi
fi

rm -f panel.zip

if [ ! -f $setup_path/server/panel/tools.py ];then
	echo -e "\033[31mERROR: Failed to download, please try again!\033[0m";
	echo '============================================'
	exit;
fi

rm -f $setup_path/server/panel/class/*.pyc
rm -f $setup_path/server/panel/*.pyc



chmod +x /etc/init.d/bt
chkconfig --add bt
chkconfig --level 2345 bt on
chmod -R 600 $setup_path/server/panel
chmod -R +x $setup_path/server/panel/script
ln -sf /etc/init.d/bt /usr/bin/bt
echo "$port" > $setup_path/server/panel/data/port.pl
/etc/init.d/bt start

password=`cat /etc/passwd | head -n 1 | md5sum | head -c 8`
sleep 1
admin_auth='/www/server/panel/data/admin_path.pl'
if [ ! -f $admin_auth ];then
	auth_path=`cat /etc/passwd | head -n 1 | md5sum | head -c 8`
	echo "/$auth_path" > $admin_auth
fi
auth_path=`cat $admin_auth`
cd $setup_path/server/panel/
python -m py_compile tools.py
username=tgbaota
cd ~
echo "$password" > $setup_path/server/panel/default.pl
chmod 600 $setup_path/server/panel/default.pl
/etc/init.d/bt restart
sleep 3
isStart=`ps aux |grep 'BT-Panel'|grep -v grep|awk '{print $2}'`
userbt(){
bt  1>/dev/null  <<EOF
6
tgbaota
EOF
sleep 2
newpassword=$(cat /www/server/panel/default.pl)
cd /www/server/panel && python tools.pyc panel $newpassword   1>/dev/null
}
btport(){
bt  1>/dev/null  <<EOF
11
EOF
sleep 3
}

if [ "$isStart" == '' ];then
	echo -e "\033[31mERROR: The BT-Panel service startup failed.\033[0m";
	echo '============================================'
	exit;
fi

if [ ! -f /root/.ssh/authorized_keys ] || [ ! -f /root/.ssh/id_rsa ];then
	if [ -f /root/.ssh/id_rsa ];then
		rm -f /root/.ssh/id_rsa /root/.ssh/id_rsa.pub
	fi
	ssh-keygen -q -t rsa -P "" -f /root/.ssh/id_rsa
fi
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

if [ -f "/etc/init.d/iptables" ];then
	sshPort=`cat /etc/ssh/sshd_config | grep 'Port ' | grep -oE [0-9] | tr -d '\n'`
	if [ "${sshPort}" != "22" ]; then
		iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport $sshPort -j ACCEPT
	fi
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 20 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport $port -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 39000:40000 -j ACCEPT
	#iptables -I INPUT -p tcp -m state --state NEW -m udp --dport 39000:40000 -j ACCEPT
	iptables -A INPUT -p icmp --icmp-type any -j ACCEPT
	iptables -A INPUT -s localhost -d localhost -j ACCEPT
	iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
	iptables -P INPUT DROP
	service iptables save
	sed -i "s#IPTABLES_MODULES=\"\"#IPTABLES_MODULES=\"ip_conntrack_netbios_ns ip_conntrack_ftp ip_nat_ftp\"#" /etc/sysconfig/iptables-config

	iptables_status=`service iptables status | grep 'not running'`
	if [ "${iptables_status}" == '' ];then
		service iptables restart
	fi
fi

if [ "${isVersion}" == '' ];then
	if [ ! -f "/etc/init.d/iptables" ];then
		sshPort=`cat /etc/ssh/sshd_config | grep 'Port ' | grep -oE [0-9] | tr -d '\n'`
		yum install firewalld -y
		systemctl restart firewalld
		firewall-cmd --set-default-zone=public > /dev/null 2>&1
		if [ "${sshPort}" != "22" ]; then
			firewall-cmd --permanent --zone=public --add-port=$sshPort/tcp > /dev/null 2>&1
		fi
		firewall-cmd --permanent --zone=public --add-port=20/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=21/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=22/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=$port/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp > /dev/null 2>&1
		#firewall-cmd --permanent --zone=public --add-port=39000-40000/udp > /dev/null 2>&1
		firewall-cmd --reload
	fi
fi

pip install psutil chardet psutil virtualenv cryptography==2.1 > /dev/null 2>&1

if [ ! -d '/etc/letsencrypt' ];then
	yum install epel-release -y

	if [ "${country}" = "CN" ]; then
		isC7=`cat /etc/redhat-release |grep ' 7.'`
		if [ "${isC7}" == "" ];then
			wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
		else
			wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
		fi
	fi
	mkdir -p /var/spool/cron
	if [ ! -f '/var/spool/cron/root' ];then
		echo '' > /var/spool/cron/root
		chmod 600 /var/spool/cron/root
	fi
fi

wget -O acme_install.sh $download_Url/install/acme_install.sh
nohup bash acme_install.sh &> /dev/null &
sleep 1
rm -f acme_install.sh

address=""
address=`curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress`
if [ "$address" == '0.0.0.0' ] || [ "$address" == '' ];then
	isHosts=`cat /etc/hosts|grep 'www.bt.cn'`
	if [ "$isHosts" == '' ];then
		echo "" >> /etc/hosts
		echo "125.88.182.170 www.bt.cn" >> /etc/hosts
		address=`curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress`
		if [ "$address" == '' ];then
			sed -i "/bt.cn/d" /etc/hosts
		fi
	fi
fi

ipCheck=`python -c "import re; print(re.match('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$','$address'))"`
if [ "$ipCheck" == "None" ];then
	address="SERVER_IP"
fi

if [ "$address" != "SERVER_IP" ];then
	echo "$address" > $setup_path/server/panel/data/iplist.txt
fi

curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/SetupCount?type=Linux\&o=$1 > /dev/null 2>&1
if [ "$1" != "" ];then
	echo $1 > /www/server/panel/data/o.pl
	cd /www/server/panel
	python tools.py o
fi
echo /www > /var/bt_setupPath.conf
/etc/init.d/bt start
userbt
btport
echo -e "=================================================================="
echo -e "\033[32mCongratulations! Installed successfully!\033[0m"
echo -e "=================================================================="
echo  "Bt-Panel: http://$address:$port"
echo -e "username: $username"
echo -e "password: $password"
echo -e "\033[33mWarning:\033[0m"
echo -e "\033[33mIf you cannot access the panel, \033[0m"
echo -e "\033[33mrelease the following port (2222|888|80|443|20|21) in the security group\033[0m"
echo -e "=================================================================="

endTime=`date +%s`
((outTime=($endTime-$startTime)/60))
echo -e "Time consumed:\033[32m $outTime \033[0mMinute!"
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi	
}

#安装Verynginx
Verynginx_install(){
yum install -y make cmake gcc gcc-c++ patch autoconf automake libpng-devel libjpeg-devel zlib libxml2-devel ncurses-devel bison libtool-ltdl-devel libiconv libmcrypt mhash mcrypt postgresql-devel libgeoip-dev geoip-devel pcre-devel openssl-devel freetype-devel libcurl-devel readline-devel curl
firewall-cmd --zone=public --add-port=80/tcp --permanent && firewall-cmd --reload 
firewall-cmd --zone=public --add-port=443/tcp --permanent && firewall-cmd --reload 
cat > /etc/security/limits.conf<<EOF
*    soft    nofile    65536
*    hard    nofile    65536
*    soft    noproc    10240
*    hard    noproc    10240
EOF
mkdir -p /tg && cd /tg
wget -c -t0 -P /tg http://dl.tg9.me/openresty/openresty-1.21.4.2.tar.gz 
wget -c -t0 -P /tg http://dl.tg9.me/openresty/openssl-1.1.1c.tar.gz
wget -c -t0 -P /tg http://dl.tg9.me/openresty/zlib-1.2.11.tar.gz
wget -c -t0 -P /tg http://dl.tg9.me/openresty/GeoIP-1.6.12.tar.gz
wget -c -t0 -P /tg http://dl.tg9.me/openresty/nginx_upstream_check_module.tar.gz
tar -xf openresty-1.21.4.2.tar.gz
tar -xf openssl-1.1.1c.tar.gz
tar -xf zlib-1.2.11.tar.gz
tar -xf GeoIP-1.6.12.tar.gz
tar -xf nginx_upstream_check_module.tar.gz && ll

cd /tg/GeoIP-*/
./configure --prefix=/usr/local/GeoIP
make -j `grep processor /proc/cpuinfo | wc -l` && make install
echo '/usr/local/GeoIP/lib' > /etc/ld.so.conf.d/geoip.conf
echo '/usr/local/lib' >> /etc/ld.so.conf.d/geoip.conf
ldconfig

cd /tg/openssl-*/
./config --prefix=/usr/local/openssl
./config -t
make -j `grep processor /proc/cpuinfo | wc -l` && make install

cd /tg/zlib-*/
./configure  --prefix=/usr/local/zlib
make -j `grep processor /proc/cpuinfo | wc -l` && make install
 
wget http://dl.tg9.me/openresty/Geoip/GeoIP.dat.gz
gunzip GeoIP.dat.gz
mkdir /usr/local/share/GeoIP
mv GeoIP.dat /usr/local/share/GeoIP/

id -u www >/dev/null 2>&1
[ $? -ne 0 ] && groupadd www && useradd -s /sbin/nologin -g www -M www

cd /tg/openresty-1.21.4.2/bundle/nginx-1.21.4
patch -p1 < /tg/nginx_upstream_check_module/check_1.14.0+.patch
cd /tg/openresty-*
sed -i 's/1.21.4/1.2.20231030/g' bundle/nginx-1.21.4/src/core/nginx.h
sed -i 's/openresty/BY/g' bundle/nginx-1.21.4/src/core/nginx.h
sed -i 's/openresty/BY/g' bundle/nginx-1.21.4/src/http/ngx_http_header_filter_module.c
sed -i 's/openresty/BY/g' bundle/nginx-1.21.4/src/http/ngx_http_special_response.c
./configure \
--prefix=/usr/local \
--user=www \
--group=www \
--with-luajit \
--with-stream \
--with-poll_module \
--with-http_iconv_module \
--with-http_realip_module \
--with-ld-opt="-Wl,-rpath,/usr/local/lib" \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_postgres_module \
--with-http_mp4_module \
--with-http_flv_module \
--with-http_ssl_module \
--with-http_sub_module \
--with-http_v2_module \
--with-http_geoip_module \
--without-http_empty_gif_module \
--without-http_redis2_module \
--with-openssl=/tg/openssl-1.1.1c \
--with-zlib=/tg/zlib-1.2.11 \
--add-module=/tg/nginx_upstream_check_module 

make -j `grep processor /proc/cpuinfo | wc -l` && make install

#rm -f /usr/local/nginx/conf/nginx.conf
rm -f /usr/local/nginx/html/*

#wget -c -t0 -P /usr/local/nginx/conf http://dl.tg9.me/openresty/conf/nginx.conf
wget -c -t0 -P /usr/local/nginx/html http://dl.tg9.me/openresty/conf/index.html

cat >> /usr/lib/systemd/system/nginx.service<<EOF
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable nginx.service
systemctl start nginx.service

ln -s /usr/local/nginx/sbin/nginx /usr/bin/
history -c

#========================================================================
#######ALL服务器
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=443/tcp --permanent
firewall-cmd --zone=public --add-port=6868/tcp --permanent
firewall-cmd --zone=public --add-port=6869/tcp --permanent
firewall-cmd --reload
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#系统初始化
system_init(){
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
# TG Server_initialize script
# www.offensivesec.com By:Flame

export PATH
export GREP_OPTIONS='--color=auto' 
export GREP_COLOR='01;04;32'

if [ $(id -u) != "0" ]; then	
				echo 'This script must be run as root!'
				echo "Error: Please use root user login"
		exit 1
fi

echo -e "\033[34;32m#########################################\033[0m"
		echo -e "\033[34;32m#########################################\033[0m"
			read -p "Please enter this server hostname:" HOSTNAME
#			read -p "Please enter lottery user password:" LOTPASSWORD
					HOSTNAME=${HOSTNAME}
					LOTPASSWORD=${LOTPASSWORD}
		echo "Hostname is:${HOSTNAME}" 
#		echo "lottery user password is:${LOTPASSWORD}" 
		echo -e "\033[34;32m#########################################\033[0m"
		echo -e "\033[34;32m#########################################\033[0m"
#修改主机名
cat > /etc/hostname <<EOF
$HOSTNAME
EOF

#hostname  $HOSTNAME

#创建nginx软链接
if [ ! -f /usr/local/nginx/sbin/nginx  ]; then
	echo -e "\033[31m Nginx not file \033[0m"
	sleep 3
else
	if [ -f /sbin/nginx  ]; then
	echo -e "\033[31m The nginx link already exists \033[0m"
	sleep 3
	else
        `ln -s /usr/local/nginx/sbin/nginx /sbin/`
	echo "Create nginx links to successful!"
	sleep 3
	fi
fi



#update system
yum update -y ; yum install -y wget unzip fping gcc gcc-c++ ntp expect git make mlocalte mlocate psmisc iotop net-tools bash-completion telnet lsof vim screen iotop mtr sysstat dmidecode lrzsz  gdb libaio-devel ncurses-devel ;yum -y remove postfix sendmail rpcbind

#iotop安装
git clone git://repo.or.cz/iotop.git
cd iotop && python setup.py install

#htop安装
wget https://hisham.hm/htop/releases/2.2.0/htop-2.2.0.tar.gz
tar -xf htop-2.2.0.tar.gz
cd htop-2.2.0
./configure && make install

#nload安装
wget http://www.roland-riegel.de/nload/nload-0.7.2.tar.gz 
tar zxvf nload-0.7.2.tar.gz 
cd nload-0.7.2 
./configure
make;make install

#selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
setenforce 0 

#同步上海时间 && 开机同步一次
\cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
ntpdate -u pool.ntp.org
echo 'ntpdate -u pool.ntp.org' >> /etc/rc.d/rc.local
chmod 744  /etc/rc.d/rc.local

#计划任务每天同步时间
crontab /etc/crontab && sleep 1
echo '00 5 * * *  root  /usr/sbin/ntpdate -u pool.ntp.org &>/dev/null 2>&1 || ntpdate -u time.nist.gov &>/dev/null 2>&1 || ntpdate -u  ntp1.aliyun.com &>/dev/null 2>&1  || ntpdate -u  ntp2.aliyun.com &>/dev/null 2>&1 || ntpdate -u  ntp3.aliyun.com &>/dev/null 2>&1 || ntpdate -u  ntp4.aliyun.com  &>/dev/null 2>&1 ' >> /etc/crontab
systemctl restart crond ; systemctl enable crond

#安装JDK
wget http://dl.tg9.me/JDK/jdk-8u171-linux-x64.tar.gz
mkdir /usr/local/jdk
tar xzf jdk-8u171-linux-x64.tar.gz
cp -rf jdk1.8.0_171/* /usr/local/jdk
cat >> /etc/profile<<EOF

export JAVA_HOME=/usr/local/jdk
export JAVA_BIN=\$JAVA_HOME/bin
export PATH=\$PATH:\$JAVA_HOME/bin
export CLASSPATH=.:\$JAVA_HOME/lib/dt.jar:\$JAVA_HOME/lib/tools.jar
export PATH=\$JAVA_HOME/bin:\$JRE_HOME/bin:$PATH
EOF
source /etc/profile

#安装maven
wget http://dl.tg9.me/MVN/apache-maven-3.6.0-bin.tar.gz
tar -xf apache-maven-3.6.0-bin.tar.gz
mkdir /usr/local/maven/
cp -rf apache-maven-3.6.0/* /usr/local/maven/
cat >> /etc/profile.d/maven.sh<<EOF

export MAVEN_HOME=/usr/local/maven
export PATH=\$PATH:\$MAVEN_HOME/bin
EOF
source /etc/profile.d/maven.sh

#添加防火墙端口放行
echo "firewall-cmd --zone=public --add-port=8090/tcp --permanent"
firewall-cmd --zone=public --add-port=8090/tcp --permanent
echo "firewall-cmd --zone=public --add-port=5555/tcp --permanent"
firewall-cmd --zone=public --add-port=5555/tcp --permanent
echo "firewall-cmd --zone=public --add-port=9000/tcp --permanent"
firewall-cmd --zone=public --add-port=9000/tcp --permanent
echo "firewall-cmd --zone=public --add-port=6868/tcp --permanent"
firewall-cmd --zone=public --add-port=6868/tcp --permanent
echo "firewall-cmd --zone=public --add-port=6869/tcp --permanent"
firewall-cmd --zone=public --add-port=6869/tcp --permanent
echo "firewall-cmd --zone=public --add-port=9010/tcp --permanent"
firewall-cmd --zone=public --add-port=9010/tcp --permanent
echo "刷新firewalld中..."
firewall-cmd --reload
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#安装BBR内核
installbbr(){
	kernel_version="4.11.8"
	if [[ "${release}" == "centos" ]]; then
		rpm --import http://${github}/bbr/${release}/RPM-GPG-KEY-elrepo.org
		yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-${kernel_version}.rpm
		yum remove -y kernel-headers
		yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-headers-${kernel_version}.rpm
		yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-devel-${kernel_version}.rpm
	elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then
		mkdir bbr && cd bbr
		wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
		wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/linux-headers-${kernel_version}-all.deb
		wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-headers-${kernel_version}.deb
		wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-image-${kernel_version}.deb
	
		dpkg -i libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
		dpkg -i linux-headers-${kernel_version}-all.deb
		dpkg -i linux-headers-${kernel_version}.deb
		dpkg -i linux-image-${kernel_version}.deb
		cd .. && rm -rf bbr
	fi
	detele_kernel
	BBR_grub
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#启用BBR
startbbr(){
	remove_all
	echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
	echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
	sysctl -p
	echo -e "${Info}BBR启动成功！"
	sleep 3
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#编译并启用BBR魔改
startbbrmod(){
	remove_all
	if [[ "${release}" == "centos" ]]; then
		yum install -y make gcc
		mkdir bbrmod && cd bbrmod
		wget -N --no-check-certificate http://${github}/bbr/tcp_tsunami.c
		echo "obj-m:=tcp_tsunami.o" > Makefile
		make -C /lib/modules/$(uname -r)/build M=`pwd` modules CC=/usr/bin/gcc
		chmod +x ./tcp_tsunami.ko
		cp -rf ./tcp_tsunami.ko /lib/modules/$(uname -r)/kernel/net/ipv4
		insmod tcp_tsunami.ko
		depmod -a
	else
		apt-get update
		if [[ "${release}" == "ubuntu" && "${version}" = "14" ]]; then
			apt-get -y install build-essential
			apt-get -y install software-properties-common
			add-apt-repository ppa:ubuntu-toolchain-r/test -y
			apt-get update
		fi
		apt-get -y install make gcc
		mkdir bbrmod && cd bbrmod
		wget -N --no-check-certificate http://${github}/bbr/tcp_tsunami.c
		echo "obj-m:=tcp_tsunami.o" > Makefile
		ln -s /usr/bin/gcc /usr/bin/gcc-4.9
		make -C /lib/modules/$(uname -r)/build M=`pwd` modules CC=/usr/bin/gcc-4.9
		install tcp_tsunami.ko /lib/modules/$(uname -r)/kernel
		cp -rf ./tcp_tsunami.ko /lib/modules/$(uname -r)/kernel/net/ipv4
		depmod -a
	fi
	

	echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
	echo "net.ipv4.tcp_congestion_control=tsunami" >> /etc/sysctl.conf
	sysctl -p
    cd .. && rm -rf bbrmod
	echo -e "${Info}魔改版BBR启动成功！"
	sleep 2
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#卸载全部加速
remove_all(){
	rm -rf bbrmod
	sed -i '/net.core.default_qdisc/d' /etc/sysctl.conf
    sed -i '/net.ipv4.tcp_congestion_control/d' /etc/sysctl.conf
    sed -i '/fs.file-max/d' /etc/sysctl.conf
	sed -i '/net.core.rmem_max/d' /etc/sysctl.conf
	sed -i '/net.core.wmem_max/d' /etc/sysctl.conf
	sed -i '/net.core.rmem_default/d' /etc/sysctl.conf
	sed -i '/net.core.wmem_default/d' /etc/sysctl.conf
	sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf
	sed -i '/net.core.somaxconn/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_tw_recycle/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_keepalive_time/d' /etc/sysctl.conf
	sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_rmem/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_wmem/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_mtu_probing/d' /etc/sysctl.conf
	sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf
	sed -i '/fs.inotify.max_user_instances/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf
	sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf
	sed -i '/net.ipv4.route.gc_timeout/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_synack_retries/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_syn_retries/d' /etc/sysctl.conf
	sed -i '/net.core.somaxconn/d' /etc/sysctl.conf
	sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_timestamps/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_orphans/d' /etc/sysctl.conf
	if [[ -e /appex/bin/serverSpeeder.sh ]]; then
		wget --no-check-certificate -O appex.sh https://raw.githubusercontent.com/0oVicero0/serverSpeeder_Install/master/appex.sh && chmod +x appex.sh && bash appex.sh uninstall
		rm -f appex.sh
	fi
	clear
	echo -e "${Info}:清除加速完成。"
	sleep 1s
}

#优化系统配置
optimizing_system(){
	sed -i '/fs.file-max/d' /etc/sysctl.conf
	sed -i '/fs.inotify.max_user_instances/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf
	sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf
	sed -i '/net.ipv4.route.gc_timeout/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_synack_retries/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_syn_retries/d' /etc/sysctl.conf
	sed -i '/net.core.somaxconn/d' /etc/sysctl.conf
	sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_timestamps/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_orphans/d' /etc/sysctl.conf
	sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf
echo	"fs.file-max = 1000000
	fs.inotify.max_user_instances = 8192
	net.ipv4.tcp_syncookies = 1
	net.ipv4.tcp_fin_timeout = 30
	net.ipv4.tcp_tw_reuse = 1
	net.ipv4.ip_local_port_range = 1024 65000
	net.ipv4.tcp_max_syn_backlog = 16384
	net.ipv4.tcp_max_tw_buckets = 6000
	net.ipv4.route.gc_timeout = 100
	net.ipv4.tcp_syn_retries = 1
	net.ipv4.tcp_synack_retries = 1
	net.core.somaxconn = 32768
	net.core.netdev_max_backlog = 32768
	net.ipv4.tcp_timestamps = 0
	net.ipv4.tcp_max_orphans = 32768
	# forward ipv4
	net.ipv4.ip_forward = 1">>/etc/sysctl.conf
	sysctl -p
	echo "*               soft    nofile           1000000
*               hard    nofile          1000000">/etc/security/limits.conf
	echo "ulimit -SHn 1000000">>/etc/profile
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#添加lottery用户
Create_lottery(){
ln -s /home/lottery/tg/run_project /root/tg
cp /usr/local/jdk/jre/lib/security/policy/unlimited/*.jar /usr/local/jdk/jre/lib/security/
useradd lottery
read -p "Please enter lottery user password:" LOTPASSWORD
echo $LOTPASSWORD | passwd --stdin "lottery"
su - lottery -c "source /etc/profile.d/maven.sh"
su - lottery -c "mkdir -p /home/lottery/tg/{lottery_project,run_project}"
su - lottery -c "cd /home/lottery/tg/run_project && wget http://dl.tg9.me/default/runscript.sh && chmod 777 runscript.sh && ll && cd"
su - lottery -c "mkdir -p /home/lottery/tg/{lottery_project,run_project}"
su - lottery -c "wget http://dl.tg9.me/default/ip.dat"

#su - lottery -c "ssh-keygen -t rsa -N '' -f id_rsa -q"
cat >> /home/lottery/create_key.sh <<EOF
#!/bin/bash
ssh-keygen -t rsa -N '' -f id_rsa -q
expect <<eof
spawn git clone git@47.52.90.110:tgjava/lottery.git
expect {
"*yes/no" { send "yes\r"; exp_continue }
}
eof
EOF
chmod 777 /home/lottery/create_key.sh
su - lottery -s /bin/sh /home/lottery/create_key.sh 
rm -f /home/lottery/create_key.sh
mkdir -p /home/lottery/.ssh/
mv /home/lottery/id_rsa* /home/lottery/.ssh/
chown -R lottery.lottery /home/lottery/.ssh 
chown -R lottery.lottery /home/lottery/tg/

#修改nginx-html权限
mkdir -p /usr/local/nginx/html/bak
chmod -R 775 /usr/local/nginx/html
chown -R root:lottery /usr/local/nginx/html

clear && cat /home/lottery/.ssh/id_rsa.pub
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
	
}
#安装Zabbix客户端
install_zabbixClient(){
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
RLS=`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`
HOSTNAME=`hostname`

if [ $(id -u) != "0" ]; then
                echo "Error: Please use root user login"
    exit 1
fi

if [ -s /etc/selinux/config ]; then
        sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
        setenforce 0
fi

#read -p "Enter zabbix server ip address(default：3.0.159.208):" ZSERVERIP
        ZSERVERIP=${ZSERVERIP:=3.0.159.208}
if [ "$RLS" = "6" ]; then
                rpm -i https://repo.zabbix.com/zabbix/4.4/rhel/6/x86_64/zabbix-release-4.4-1.el6.noarch.rpm
        else
                rpm -i https://repo.zabbix.com/zabbix/4.4/rhel/7/x86_64/zabbix-release-4.4-1.el7.noarch.rpm
fi
yum install -y zabbix-agent net-tools
        sed -i "s/^Server=127.0.0.1/Server=$ZSERVERIP/g" /etc/zabbix/zabbix_agentd.conf
        sed -i "s/^ServerActive=127.0.0.1/ServerActive=$ZSERVERIP/g" /etc/zabbix/zabbix_agentd.conf
        sed -i "s/^Hostname=Zabbix server/Hostname=$HOSTNAME/g" /etc/zabbix/zabbix_agentd.conf
if [ "$RLS" = "6" ]; then
        /sbin/iptables -I INPUT -s $ZSERVERIP -j ACCEPT
        /sbin/iptables -I INPUT -s $ZSERVERIP -p tcp --dport 10050 -j ACCEPT
        service iptables save && service iptables restart && service zabbix-agent start && chkconfig zabbix-agent on
        else
        firewall-cmd --zone=public --add-port=10050/tcp --permanent
        systemctl start zabbix-agent.service && systemctl enable zabbix-agent.service && firewall-cmd --reload
fi

#done
clear ;
check_port() {
        echo "正在检测Zabbix服务..."
        netstat -tlpn | grep "\b$1\b"
}
if check_port 10050
then
        echo "Zabbix 已成功启动！"
else
        echo "Zabbix 未启动成功！"
        DATE_N=`date "+%Y-%m%d %H:%M:%S"`
        echo "时间：${DATE_N}" >> zabbix.log #记录死亡日志
fi

	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#MySQL基准测试
Mysql_test(){
	echo "功能开发中 敬请期待！"
	sleep 2
	start_menu
}

#检测各项服务是否安装完成
Testing(){
	if  [ ! -x /usr/local/bin/openresty ];then
		echo -e "\033[31m\033[01m\033[05m[ nginx服务安装异常 ]\033[0m"
	else
		echo -e "\033[32m\033[01m\033[05m[ nginx服务正常 ]\033[0m"
	fi
	if  [ ! -x /usr/local/jdk/bin/java ];then
		echo -e "\033[31m\033[01m\033[05m[ JDK服务安装异常 ]\033[0m"
	else
		echo -e "\033[32m\033[01m\033[05m[ JDK服务正常 ]\033[0m"
	fi
	if  [ ! -x /usr/local/maven/bin/mvn ];then
		echo -e "\033[31m\033[01m\033[05m[ mvn服务安装异常 ]\033[0m"
	else
		echo -e "\033[32m\033[01m\033[05m[ mvn服务正常 ]\033[0m"
	fi
	if  [ ! -x /sbin/iotop ];then
		echo -e "\033[31m\033[01m\033[05m[ iotop服务安装异常 ]\033[0m"
	else
		echo -e "\033[32m\033[01m\033[05m[ iotop服务正常 ]\033[0m"
	fi
	if  [ ! -x /usr/local/bin/htop ];then
		echo -e "\033[31m\033[01m\033[05m[ htop服务安装异常 ]\033[0m"
	else
		echo -e "\033[32m\033[01m\033[05m[ htop服务正常 ]\033[0m"
	fi
	if  [ ! -x /usr/local/bin/nload ];then
		echo -e "\033[31m\033[01m\033[05m[ nload服务安装异常 ]\033[0m"
	else
		echo -e "\033[32m\033[01m\033[05m[ nload服务正常 ]\033[0m"
	fi
	bbr_status=`grep "net.ipv4.tcp_congestion_control" /etc/sysctl.conf | awk -F "=" '{print $2}'`
	if [[ ${bbr_status} == "bbr" ]]; then
		echo -e "\033[32m\033[01m\033[05m[ bbr服务正常 ]\033[0m"
	else
		echo -e "\033[31m\033[01m\033[05m[ bbr服务安装异常 ]\033[0m"
	fi
	zabbix_port=`netstat -nlt|grep 10050|wc -l`
	if [ $zabbix_port -gt 1 ];then
		echo -e "\033[32m\033[01m\033[05m[ zabbix服务正常 ]\033[0m"
	else
		echo -e "\033[31m\033[01m\033[05m[ zabbix服务异常 ]\033[0m"
	fi

	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#一键添加开机启动程序
start_java(){
if [  ! -f /etc/start_java.sh ];then
chmod  +x /etc/rc.d/rc.local
cat > /etc/start_java.sh <<EOF
#!/bin/bash
#开机启动java程序
export JAVA_HOME=/usr/local/jdk
export JAVA_BIN=\$JAVA_HOME/bin
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/root/bin:\$JAVA_HOME/bin
export CLASSPATH=.:\$JAVA_HOME/lib/dt.jar:\$JAVA_HOME/lib/tools.jar
export PATH=\$JAVA_HOME/bin:/bin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/root/bin
sleep 5s


/usr/bin/consul agent --config-dir=/usr/local/consul/etc/ >/dev/null 2>&1 &
sleep 10s
port_consul=\`netstat -nlt|grep 8500|wc -l\`
if [ \$port_consul -eq 1 ];then
	echo "run consul"
else
	/usr/bin/consul agent --config-dir=/usr/local/consul/etc/ >/dev/null 2>&1 &
fi

if [  ! -f /root/tg/lottery-api.jar ];then
	echo "not file"
else 
	port_api=\`netstat -nlt|grep 4848|wc -l\`
	if [ \$port_api -eq 1 ];then
		echo "run lottery-api.jar"
	else
		echo "run lottery-api.jar"
		cd  /root/tg 
		mv lottery-api.log  /tmp/lottery-api.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-api.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-api.jar > lottery-api.log  2>&1 &
	fi
fi
sleep 2s
if [  ! -f /root/tg/lottery-admin.jar ];then
        echo "not file"
else
	port_admin=\`netstat -nlt|grep 8090|wc -l\`
	if [ \$port_admin -eq 1 ];then
		echo "run lottery-admin.jar"
	else
		cd /root/tg 
		mv lottery-admin.log  /tmp/lottery-admin.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-admin.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-admin.jar > lottery-admin.log 2>&1 &
	fi
fi
sleep 2s
if [  ! -f /root/tg/lottery-task.jar ];then
        echo "not file"
else
	port_task=\`netstat -nlt|grep 9010|wc -l\`
	if [ \$port_task -eq 1 ];then
		echo "run lottery-task.jar"
	else
		cd /root/tg 
		mv lottery-task.log  /tmp/lottery-task.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-task.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-task.jar > lottery-task.log 2>&1 &
	fi
fi
sleep 2s
if [  ! -f /root/tg/lottery-3rd-party.jar ];then
        echo "not file"
else
	port_3rd=\`netstat -nlt|grep 3838|wc -l\`
	if [ \$port_3rd -eq 1 ];then
		echo "run lottery-3rd-party.jar"
	else
		cd /root/tg 
		mv lottery-3rd-party.log  /tmp/lottery-3rd-party.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-3rd-party.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-3rd-party.jar > lottery-3rd-party.log 2>&1 &
	fi
fi
sleep 150s

if [  ! -f /root/tg/lottery-api.jar ];then
	echo "not file"
else 
	port_api=\`netstat -nlt|grep 4848|wc -l\`
	if [ \$port_api -eq 1 ];then
		echo "run lottery-api.jar"
	else
		echo "run lottery-api.jar"
		cd  /root/tg 
		mv lottery-api.log  /tmp/lottery-api.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-api.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-api.jar > lottery-api.log  2>&1 &
	fi
fi
sleep 2s
if [  ! -f /root/tg/lottery-admin.jar ];then
        echo "not file"
else
	port_admin=\`netstat -nlt|grep 8090|wc -l\`
	if [ \$port_admin -eq 1 ];then
		echo "run lottery-admin.jar"
	else
		cd /root/tg 
		mv lottery-admin.log  /tmp/lottery-admin.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-admin.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-admin.jar > lottery-admin.log 2>&1 &
	fi
fi
sleep 2s
if [  ! -f /root/tg/lottery-task.jar ];then
        echo "not file"
else
	port_task=\`netstat -nlt|grep 9010|wc -l\`
	if [ \$port_task -eq 1 ];then
		echo "run lottery-task.jar"
	else
		cd /root/tg 
		mv lottery-task.log  /tmp/lottery-task.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-task.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-task.jar > lottery-task.log 2>&1 &
	fi
fi
sleep 2s
if [  ! -f /root/tg/lottery-3rd-party.jar ];then
        echo "not file"
else
	port_3rd=\`netstat -nlt|grep 3838|wc -l\`
	if [ \$port_3rd -eq 1 ];then
		echo "run lottery-3rd-party.jar"
	else
		cd /root/tg 
		mv lottery-3rd-party.log  /tmp/lottery-3rd-party.log\`date +'%Y%m%d%H%M%S'\`
		ps -ef|grep lottery-3rd-party.jar|grep -v grep|grep -v PPID|awk '{ print \$2}'| xargs kill -9 
		nohup java -Duser.timezone=GMT+8 -jar lottery-3rd-party.jar > lottery-3rd-party.log 2>&1 &
	fi
fi


EOF
echo "/etc/start_java.sh" >> /etc/rc.local 
chmod +x /etc/start_java.sh
echo -e "\033[32m\033[01m\033[05m[ start_java.sh 创建完成 ]\033[0m"
	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
else 
	echo "start_java.sh  已存在"
		read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
fi
}

#一键初始化系统
install_all(){
read -p "Please enter this server hostname:" HOSTNAME
HOSTNAME=${HOSTNAME}
#修改主机名
cat > /etc/hostname <<EOF
$HOSTNAME
EOF

#修改防火墙信任区域
firewall_port=`firewall-cmd --list-all |awk '{print $1}'|awk 'NR==1{print}'`
if [ $firewall_port != public ];then
      firewall-cmd --set-default-zone=public
else
        echo "Firewalls are public areas!"
fi

#检测防火墙是否启动（针对亚马逊的非标准模板主机）
service=firewalld
ser=`/usr/bin/pgrep $service`
if [ "$ser" != "" ];then
	firewall-cmd --permanent --zone=public --add-port=20/tcp
	firewall-cmd --permanent --zone=public --add-port=21/tcp 
	firewall-cmd --permanent --zone=public --add-port=22/tcp 
	firewall-cmd --permanent --zone=public --add-port=2222/tcp
	firewall-cmd --permanent --zone=public --add-port=5555/tcp 
	firewall-cmd --permanent --zone=public --add-port=6868/tcp
	firewall-cmd --permanent --zone=public --add-port=6869/tcp 
	firewall-cmd --permanent --zone=public --add-port=8090/tcp 
	firewall-cmd --permanent --zone=public --add-port=9000/tcp
	firewall-cmd --permanent --zone=public --add-port=9010/tcp 
	firewall-cmd --permanent --zone=public --add-port=10050/tcp
	firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp 
	firewall-cmd --permanent --zone=public --add-port=63240/tcp
	firewall-cmd --reload
else
	if  [ ! -x /bin/firewall-cmd ];then
		yum -y install firewalld
		systemctl unmask  firewalld
		systemctl restart firewalld 						  
		firewall-cmd --permanent --zone=public --add-port=20/tcp
		firewall-cmd --permanent --zone=public --add-port=21/tcp 
		firewall-cmd --permanent --zone=public --add-port=22/tcp 
		firewall-cmd --permanent --zone=public --add-port=2222/tcp
		firewall-cmd --permanent --zone=public --add-port=5555/tcp 
		firewall-cmd --permanent --zone=public --add-port=6868/tcp
		firewall-cmd --permanent --zone=public --add-port=6869/tcp 
		firewall-cmd --permanent --zone=public --add-port=8090/tcp 
		firewall-cmd --permanent --zone=public --add-port=9000/tcp
		firewall-cmd --permanent --zone=public --add-port=9010/tcp 
		firewall-cmd --permanent --zone=public --add-port=10050/tcp
		firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp 
		firewall-cmd --permanent --zone=public --add-port=63240/tcp
		firewall-cmd --reload
	else 
		systemctl unmask  firewalld
		systemctl restart firewalld 						  
		firewall-cmd --permanent --zone=public --add-port=20/tcp
		firewall-cmd --permanent --zone=public --add-port=21/tcp 
		firewall-cmd --permanent --zone=public --add-port=22/tcp 
		firewall-cmd --permanent --zone=public --add-port=2222/tcp
		firewall-cmd --permanent --zone=public --add-port=5555/tcp 
		firewall-cmd --permanent --zone=public --add-port=6868/tcp
		firewall-cmd --permanent --zone=public --add-port=6869/tcp 
		firewall-cmd --permanent --zone=public --add-port=8090/tcp 
		firewall-cmd --permanent --zone=public --add-port=9000/tcp
		firewall-cmd --permanent --zone=public --add-port=9010/tcp 
		firewall-cmd --permanent --zone=public --add-port=10050/tcp
		firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp 
		firewall-cmd --permanent --zone=public --add-port=63240/tcp
		firewall-cmd --reload
	fi
fi

yum install -y make cmake gcc gcc-c++ patch autoconf automake libpng-devel libjpeg-devel zlib libxml2-devel ncurses-devel bison libtool-ltdl-devel libiconv libmcrypt mhash mcrypt postgresql-devel libgeoip-dev geoip-devel pcre-devel openssl-devel freetype-devel libcurl-devel readline-devel curl
firewall-cmd --zone=public --add-port=80/tcp --permanent && firewall-cmd --reload 
firewall-cmd --zone=public --add-port=443/tcp --permanent && firewall-cmd --reload 
cat > /etc/security/limits.conf<<EOF
*    soft    nofile    65536
*    hard    nofile    65536
*    soft    noproc    10240
*    hard    noproc    10240
EOF
mkdir -p /tg && cd /tg
wget -c -t0 -P /tg http://dl.tg9.me/openresty/openresty-1.21.4.2.tar.gz 
wget -c -t0 -P /tg http://dl.tg9.me/openresty/openssl-1.1.1c.tar.gz
wget -c -t0 -P /tg http://dl.tg9.me/openresty/zlib-1.2.11.tar.gz
wget -c -t0 -P /tg http://dl.tg9.me/openresty/GeoIP-1.6.12.tar.gz
wget -c -t0 -P /tg http://dl.tg9.me/openresty/nginx_upstream_check_module.tar.gz
tar -xf openresty-1.21.4.2.tar.gz
tar -xf openssl-1.1.1c.tar.gz
tar -xf zlib-1.2.11.tar.gz
tar -xf GeoIP-1.6.12.tar.gz
tar -xf nginx_upstream_check_module.tar.gz && ll

cd /tg/GeoIP-*/
./configure --prefix=/usr/local/GeoIP
make -j `grep processor /proc/cpuinfo | wc -l` && make install
echo '/usr/local/GeoIP/lib' > /etc/ld.so.conf.d/geoip.conf
echo '/usr/local/lib' >> /etc/ld.so.conf.d/geoip.conf
ldconfig

cd /tg/openssl-*/
./config --prefix=/usr/local/openssl
./config -t
make -j `grep processor /proc/cpuinfo | wc -l` && make install

cd /tg/zlib-*/
./configure  --prefix=/usr/local/zlib
make -j `grep processor /proc/cpuinfo | wc -l` && make install
 
wget http://dl.tg9.me/openresty/Geoip/GeoIP.dat.gz
gunzip GeoIP.dat.gz
mkdir /usr/local/share/GeoIP
mv GeoIP.dat /usr/local/share/GeoIP/

id -u www >/dev/null 2>&1
[ $? -ne 0 ] && groupadd www && useradd -s /sbin/nologin -g www -M www

cd /tg/openresty-1.21.4.2/bundle/nginx-1.21.4.2
patch -p1 < /tg/nginx_upstream_check_module/check_1.14.0+.patch
cd /tg/openresty-*
sed -i 's/1.21.4/1.2.20231030/g' bundle/nginx-1.21.4/src/core/nginx.h
sed -i 's/openresty/BY/g' bundle/nginx-1.21.4/src/core/nginx.h
sed -i 's/openresty/BY/g' bundle/nginx-1.21.4/src/http/ngx_http_header_filter_module.c
sed -i 's/openresty/BY/g' bundle/nginx-1.21.4/src/http/ngx_http_special_response.c
./configure \
--prefix=/usr/local \
--user=www \
--group=www \
--with-luajit \
--with-stream \
--with-poll_module \
--with-http_iconv_module \
--with-http_realip_module \
--with-ld-opt="-Wl,-rpath,/usr/local/lib" \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_postgres_module \
--with-http_mp4_module \
--with-http_flv_module \
--with-http_ssl_module \
--with-http_sub_module \
--with-http_v2_module \
--with-http_geoip_module \
--without-http_empty_gif_module \
--without-http_redis2_module \
--with-openssl=/tg/openssl-1.1.1c \
--with-zlib=/tg/zlib-1.2.11 \
--add-module=/tg/nginx_upstream_check_module 

make -j `grep processor /proc/cpuinfo | wc -l` && make install

#rm -f /usr/local/nginx/conf/nginx.conf
rm -f /usr/local/nginx/html/*

#wget -c -t0 -P /usr/local/nginx/conf http://dl.tg9.me/openresty/conf/nginx.conf
wget -c -t0 -P /usr/local/nginx/html http://dl.tg9.me/openresty/conf/index.html

cat >> /usr/lib/systemd/system/nginx.service<<EOF
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable nginx.service
systemctl start nginx.service

ln -s /usr/local/nginx/sbin/nginx /usr/bin/
history -c

#========================================================================
#######ALL服务器
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=443/tcp --permanent
firewall-cmd --zone=public --add-port=6868/tcp --permanent
firewall-cmd --zone=public --add-port=6869/tcp --permanent
firewall-cmd --reload

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
# TG Server_initialize script
# www.offensivesec.com By:Flame

export PATH
export GREP_OPTIONS='--color=auto' 
export GREP_COLOR='01;04;32'

if [ $(id -u) != "0" ]; then	
				echo 'This script must be run as root!'
				echo "Error: Please use root user login"
		exit 1
fi

#创建nginx软链接
if [ ! -f /usr/local/nginx/sbin/nginx  ]; then
	echo -e "\033[31m Nginx not file \033[0m"
	sleep 3
else
	if [ -f /sbin/nginx  ]; then
	echo -e "\033[31m The nginx link already exists \033[0m"
	sleep 3
	else
        `ln -s /usr/local/nginx/sbin/nginx /sbin/`
	echo "Create nginx links to successful!"
	sleep 3
	fi
fi



#update system
yum update -y ; yum install -y wget unzip fping gcc gcc-c++ ntp expect git make mlocalte mlocate psmisc iotop net-tools bash-completion telnet lsof vim screen iotop mtr sysstat dmidecode lrzsz  gdb libaio-devel ncurses-devel ;yum -y remove postfix sendmail rpcbind

#iotop安装
git clone git://repo.or.cz/iotop.git
cd iotop && python setup.py install

#htop安装
wget https://hisham.hm/htop/releases/2.2.0/htop-2.2.0.tar.gz
tar -xf htop-2.2.0.tar.gz
cd htop-2.2.0
./configure && make install

#nload安装
wget http://www.roland-riegel.de/nload/nload-0.7.2.tar.gz 
tar zxvf nload-0.7.2.tar.gz 
cd nload-0.7.2 
./configure
make;make install

#selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
setenforce 0 

#同步上海时间 && 开机同步一次
\cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
ntpdate -u pool.ntp.org
echo 'ntpdate -u pool.ntp.org' >> /etc/rc.d/rc.local
chmod 744  /etc/rc.d/rc.local

#计划任务每天同步时间
crontab /etc/crontab && sleep 1
echo '00 5 * * *  root  /usr/sbin/ntpdate -u pool.ntp.org &>/dev/null 2>&1 || ntpdate -u time.nist.gov &>/dev/null 2>&1 || ntpdate -u  ntp1.aliyun.com &>/dev/null 2>&1  || ntpdate -u  ntp2.aliyun.com &>/dev/null 2>&1 || ntpdate -u  ntp3.aliyun.com &>/dev/null 2>&1 || ntpdate -u  ntp4.aliyun.com  &>/dev/null 2>&1 ' >> /etc/crontab
systemctl restart crond ; systemctl enable crond 

#安装JDK
wget http://dl.tg9.me/JDK/jdk-8u171-linux-x64.tar.gz
mkdir /usr/local/jdk
tar xzf jdk-8u171-linux-x64.tar.gz
cp -rf jdk1.8.0_171/* /usr/local/jdk
cat >> /etc/profile<<EOF

export JAVA_HOME=/usr/local/jdk
export JAVA_BIN=\$JAVA_HOME/bin
export PATH=\$PATH:\$JAVA_HOME/bin
export CLASSPATH=.:\$JAVA_HOME/lib/dt.jar:\$JAVA_HOME/lib/tools.jar
export PATH=\$JAVA_HOME/bin:\$JRE_HOME/bin:$PATH
EOF
source /etc/profile

#安装maven
wget http://dl.tg9.me/MVN/apache-maven-3.6.0-bin.tar.gz
tar -xf apache-maven-3.6.0-bin.tar.gz
mkdir /usr/local/maven/
cp -rf apache-maven-3.6.0/* /usr/local/maven/
cat >> /etc/profile.d/maven.sh<<EOF

export MAVEN_HOME=/usr/local/maven
export PATH=\$PATH:\$MAVEN_HOME/bin
EOF
source /etc/profile.d/maven.sh

#添加防火墙端口放行
echo "firewall-cmd --zone=public --add-port=8090/tcp --permanent"
firewall-cmd --zone=public --add-port=8090/tcp --permanent
echo "firewall-cmd --zone=public --add-port=5555/tcp --permanent"
firewall-cmd --zone=public --add-port=5555/tcp --permanent
echo "firewall-cmd --zone=public --add-port=9000/tcp --permanent"
firewall-cmd --zone=public --add-port=9000/tcp --permanent
echo "firewall-cmd --zone=public --add-port=6868/tcp --permanent"
firewall-cmd --zone=public --add-port=6868/tcp --permanent
echo "firewall-cmd --zone=public --add-port=6869/tcp --permanent"
firewall-cmd --zone=public --add-port=6869/tcp --permanent
echo "firewall-cmd --zone=public --add-port=9010/tcp --permanent"
firewall-cmd --zone=public --add-port=9010/tcp --permanent
echo "刷新firewalld中..."
firewall-cmd --reload

	sed -i '/fs.file-max/d' /etc/sysctl.conf
	sed -i '/fs.inotify.max_user_instances/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf
	sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf
	sed -i '/net.ipv4.route.gc_timeout/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_synack_retries/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_syn_retries/d' /etc/sysctl.conf
	sed -i '/net.core.somaxconn/d' /etc/sysctl.conf
	sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_timestamps/d' /etc/sysctl.conf
	sed -i '/net.ipv4.tcp_max_orphans/d' /etc/sysctl.conf
	sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf
	echo "fs.file-max = 1000000
fs.inotify.max_user_instances = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 32768
net.core.netdev_max_backlog = 32768
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_max_orphans = 32768
# forward ipv4
net.ipv4.ip_forward = 1">>/etc/sysctl.conf
	sysctl -p
	echo "*               soft    nofile           1000000
*               hard    nofile          1000000">/etc/security/limits.conf
	echo "ulimit -SHn 1000000">>/etc/profile

	check_version
	if [[ "${release}" == "centos" ]]; then
		if [[ ${version} -ge "6" ]]; then
			kernel_version="4.11.8"
			if [[ "${release}" == "centos" ]]; then
				rpm --import http://${github}/bbr/${release}/RPM-GPG-KEY-elrepo.org
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-${kernel_version}.rpm
				yum remove -y kernel-headers
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-headers-${kernel_version}.rpm
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-devel-${kernel_version}.rpm
			elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then
				mkdir bbr && cd bbr
				wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/linux-headers-${kernel_version}-all.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-headers-${kernel_version}.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-image-${kernel_version}.deb
			
				dpkg -i libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
				dpkg -i linux-headers-${kernel_version}-all.deb
				dpkg -i linux-headers-${kernel_version}.deb
				dpkg -i linux-image-${kernel_version}.deb
				cd .. && rm -rf bbr
			fi
			detele_kernel
			BBR_grub
		else
			echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
		fi
	elif [[ "${release}" == "debian" ]]; then
		if [[ ${version} -ge "8" ]]; then
			kernel_version="4.11.8"
			if [[ "${release}" == "centos" ]]; then
				rpm --import http://${github}/bbr/${release}/RPM-GPG-KEY-elrepo.org
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-${kernel_version}.rpm
				yum remove -y kernel-headers
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-headers-${kernel_version}.rpm
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-devel-${kernel_version}.rpm
			elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then
				mkdir bbr && cd bbr
				wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/linux-headers-${kernel_version}-all.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-headers-${kernel_version}.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-image-${kernel_version}.deb
			
				dpkg -i libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
				dpkg -i linux-headers-${kernel_version}-all.deb
				dpkg -i linux-headers-${kernel_version}.deb
				dpkg -i linux-image-${kernel_version}.deb
				cd .. && rm -rf bbr
			fi
			detele_kernel
			BBR_grub
		else
			echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
		fi
	elif [[ "${release}" == "ubuntu" ]]; then
		if [[ ${version} -ge "14" ]]; then
			kernel_version="4.11.8"
			if [[ "${release}" == "centos" ]]; then
				rpm --import http://${github}/bbr/${release}/RPM-GPG-KEY-elrepo.org
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-${kernel_version}.rpm
				yum remove -y kernel-headers
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-headers-${kernel_version}.rpm
				yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-devel-${kernel_version}.rpm
			elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then
				mkdir bbr && cd bbr
				wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/linux-headers-${kernel_version}-all.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-headers-${kernel_version}.deb
				wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-image-${kernel_version}.deb
			
				dpkg -i libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb
				dpkg -i linux-headers-${kernel_version}-all.deb
				dpkg -i linux-headers-${kernel_version}.deb
				dpkg -i linux-image-${kernel_version}.deb
				cd .. && rm -rf bbr
			fi
			detele_kernel
			BBR_grub
		else
			echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
		fi
	else
		echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
	fi

	remove_all
	echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
	echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
	sysctl -p
	echo -e "${Info}BBR启动成功！"
	sleep 3							  

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
LANG=en_US.UTF-8
is64bit=`getconf LONG_BIT`
cur_dir=`pwd`
if [ -f "/usr/bin/apt-get" ];then
	isDebian=`cat /etc/issue|grep Debian`
	if [ "$isDebian" != "" ];then
		wget -O install.sh http://download.bt.cn/install/install-ubuntu_6.0.sh && bash install.sh
		exit;
	else
		wget -O install.sh http://download.bt.cn/install/install-ubuntu_6.0.sh && sudo bash install.sh
		exit;
	fi
fi

if [ "$is64bit" != '64' ];then
	echo "====================================="
	echo "抱歉, 6.0不支持32位系统, 请使用64位系统或安装宝塔5.9!";
	exit 0;
fi

py26=$(python -V 2>&1|grep '2.6.')
if [ "$py26" != "" ];then
	echo "====================================="
	echo "抱歉, 6.0不支持Centos6.x,请安装Centos7或安装宝塔5.9";
	exit 0;
fi

CN='http://125.88.182.172:5880'

Install_Check(){
	while [ "$yes" == 'yes' ] && [ "$yes" != 'n' ]
	do
		echo -e "----------------------------------------------------"
		echo -e "已有Web环境，安装宝塔可能影响现有站点"
		echo -e "Web service is alreday installed,Can't install panel"
		echo -e "----------------------------------------------------"
		read -p "输入yes强制安装/Enter yes to force installation (yes/n): " yes;
	done 
	if [ "$yes" == 'n' ];then
		exit;
	fi
}

Web_Service_Check(){
	if [ -f "/etc/init.d/nginx" ]; then
        nginxV=$(cat /etc/init.d/nginx|grep /www/server/nginx)
        if [ "${nginxV}" = "" ];then
        	Install_Check
        fi
    fi

    if [ -f "/etc/init.d/httpd" ]; then
        httpdV=$(cat /etc/init.d/httpd|grep /www/server/apache)
        if [ "${httpdV}" = "" ];then
        	Install_Check
        fi
    fi

    if [ -f "/etc/init.d/mysqld" ]; then
        mysqlV=$(cat /etc/init.d/mysqld|grep /www/server/mysql)
        if [ "${mysqlV}" = "" ];then
        	Install_Check
        fi
    fi
}

Web_Service_Check

echo "
+----------------------------------------------------------------------
| Bt-WebPanel 6.0 FOR CentOS
+----------------------------------------------------------------------
| Copyright © 2015-2099 BT-SOFT(http://www.bt.cn) All rights reserved.
+----------------------------------------------------------------------
| The WebPanel URL will be http://SERVER_IP:2222 when installed.
+----------------------------------------------------------------------
"
get_node_url(){
	nodes=(http://125.88.182.172:5880 http://103.224.251.67 http://128.1.164.196);
	i=1;
	if [ ! -f /bin/curl ];then
		if [ -f /usr/local/curl/bin/curl ];then
			ln -sf /usr/local/curl/bin/curl /bin/curl
		else
			yum install curl -y
		fi
	fi
	for node in ${nodes[@]};
	do
		start=`date +%s.%N`
		result=`curl -sS --connect-timeout 3 -m 60 $node/check.txt`
		if [ $result = 'True' ];then
			end=`date +%s.%N`
			start_s=`echo $start | cut -d '.' -f 1`
			start_ns=`echo $start | cut -d '.' -f 2`
			end_s=`echo $end | cut -d '.' -f 1`
			end_ns=`echo $end | cut -d '.' -f 2`
			time_micro=$(( (10#$end_s-10#$start_s)*1000000 + (10#$end_ns/1000 - 10#$start_ns/1000) ))
			time_ms=$(($time_micro/1000))
			values[$i]=$time_ms;
			urls[$time_ms]=$node
			i=$(($i+1))
		fi
	done
	j=5000
	for n in ${values[@]};
	do
		if [ $j -gt $n ];then
			j=$n
		fi
	done
	if [ $j = 5000 ];then
		NODE_URL='http://download.bt.cn';
	else
		NODE_URL=${urls[$j]}
	fi
	
}
echo '---------------------------------------------';
echo "Selected download node...";
get_node_url
download_Url=$NODE_URL
echo "Download node: $download_Url";
echo '---------------------------------------------';
setup_path=/www
port='2222'
echo 2222 > /www/server/panel/data/port.pl
if [ -f $setup_path/server/panel/data/port.pl ];then
	port=`cat $setup_path/server/panel/data/port.pl`
fi

while [ "$go" == 'y' ] && [ "$go" != 'n' ]
do
	read -p "Do you want to install Bt-Panel to the $setup_path directory now?(y/n): " go;
done

if [ "$go" == 'n' ];then
	exit;
fi

path=/etc/yum.conf
isExc=`cat $path|grep httpd`
if [ "$isExc" = "" ];then
    echo "exclude=httpd nginx php mysql mairadb python-psutil python2-psutil" >> $path
fi


#数据盘自动分区
fdiskP(){
	
	for i in `cat /proc/partitions|grep -v name|grep -v ram|awk '{print $4}'|grep -v '^$'|grep -v '[0-9]$'|grep -v 'vda'|grep -v 'xvda'|grep -v 'sda'|grep -e 'vd' -e 'sd' -e 'xvd'`;
	do
		#判断指定目录是否被挂载
		isR=`df -P|grep $setup_path`
		if [ "$isR" != "" ];then
			echo "Error: The $setup_path directory has been mounted."
			return;
		fi
		
		isM=`df -P|grep '/dev/${i}1'`
		if [ "$isM" != "" ];then
			echo "/dev/${i}1 has been mounted."
			continue;
		fi
			
		#判断是否存在未分区磁盘
		isP=`fdisk -l /dev/$i |grep -v 'bytes'|grep "$i[1-9]*"`
		if [ "$isP" = "" ];then
				#开始分区
				fdisk -S 56 /dev/$i << EOF
n
p
1


wq
EOF

			sleep 5
			#检查是否分区成功
			checkP=`fdisk -l /dev/$i|grep "/dev/${i}1"`
			if [ "$checkP" != "" ];then
				#格式化分区
				mkfs.ext4 /dev/${i}1
				mkdir $setup_path
				#挂载分区
				sed -i "/\/dev\/${i}1/d" /etc/fstab
				echo "/dev/${i}1    $setup_path    ext4    defaults    0 0" >> /etc/fstab
				mount -a
				df -h
			fi
		else
			#判断是否存在Windows磁盘分区
			isN=`fdisk -l /dev/$i|grep -v 'bytes'|grep -v "NTFS"|grep -v "FAT32"`
			if [ "$isN" = "" ];then
				echo 'Warning: The Windows partition was detected. For your data security, Mount manually.';
				return;
			fi
			
			#挂载已有分区
			checkR=`df -P|grep "/dev/$i"`
			if [ "$checkR" = "" ];then
					mkdir $setup_path
					sed -i "/\/dev\/${i}1/d" /etc/fstab
					echo "/dev/${i}1    $setup_path    ext4    defaults    0 0" >> /etc/fstab
					mount -a
					df -h
			fi
			
			#清理不可写分区
			echo 'True' > $setup_path/checkD.pl
			if [ ! -f $setup_path/checkD.pl ];then
					sed -i "/\/dev\/${i}1/d" /etc/fstab
					mount -a
					df -h
			else
					rm -f $setup_path/checkD.pl
			fi
		fi
	done
}
#fdiskP

#自动挂载Swap
autoSwap()
{
	swap=`free |grep Swap|awk '{print $2}'`
	if [ $swap -gt 1 ];then
        echo "Swap total sizse: $swap";
		return;
	fi
	if [ ! -d /www ];then
		mkdir /www
	fi
	swapFile='/www/swap'
	dd if=/dev/zero of=$swapFile bs=1M count=1025
	mkswap -f $swapFile
    swapon $swapFile
    echo "$swapFile    swap    swap    defaults    0 0" >> /etc/fstab
	swap=`free |grep Swap|awk '{print $2}'`
	if [ $swap -gt 1 ];then
        echo "Swap total sizse: $swap";
		return;
	fi
	
	sed -i "/\/www\/swap/d" /etc/fstab
	rm -f $swapFile
}
autoSwap

#判断kernel-headers组件是否安装
rpm -qa | grep kernel-headers > kernel-headers.pl
kernelStatus=`cat kernel-headers.pl`
#判断华为云
huaweiLogin=`cat /etc/motd |grep 4000-955-988`
huaweiSys=`cat /etc/redhat-release | grep ' 7.'`
if [ "$kernelStatus" = "" ]; then
	if [ "$huaweiLogin" != "" ] && [ "$huaweiSys" != "" ]; then
		wget $download_Url/src/kernel-headers-3.10.0-514.el7.x86_64.rpm
		rpm -ivh kernel-headers-3.10.0-514.el7.x86_64.rpm
		rm -f kernel-headers-3.10.0-514.el7.x86_64.rpm
	else
		yum install kernel-headers -y
	fi
fi
rm -f kernel-headers.pl

yum install ntp -y
rm -rf /etc/localtime
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

echo 'Synchronizing system time...'
ntpdate 0.asia.pool.ntp.org
startTime=`date +%s`
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
for pace in python-devel python-imaging zip unzip openssl openssl-devel gcc libxml2 libxml2-devel libxslt* zlib zlib-devel libjpeg-devel libpng-devel libwebp libwebp-devel freetype freetype-devel lsof pcre pcre-devel vixie-cron crontabs icu libicu-devel c-ares;
do
	yum -y install ${pace}; 
done

if [ -f "/usr/bin/dnf" ]; then
	dnf install -y redhat-rpm-config
fi
yum install python-devel -y

py26=$(python -V 2>&1|grep '2.6.')
if [ "$py26" != "" ];then
	if [ ! -f /etc/yum.repos.d/epel.repo ];then
		wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
	fi
    if [ ! -f /usr/bin/python3 ];then
		yum install python34 python34-devel -y
		if [ ! -f /usr/bin/python3 ];then
			echo "python3.4 install error!"
			exit 0;
		fi
		isSed=$(cat /usr/bin/yum|grep /usr/bin/python2.6)
		if [ "$isSed" == "" ];then
			sed -i "s#/usr/bin/python#/usr/bin/python2.6#" /usr/bin/yum
		fi
		#rm -f /usr/bin/python2
		mv -f /usr/bin/python /usr/bin/python2_backup
		ln -sf /usr/bin/python3 /usr/bin/python
	fi
	if [ ! -f /usr/bin/pip3 ];then
		wget --no-check-certificate https://bootstrap.pypa.io/get-pip.py
		python3 get-pip.py
		mv -f /usr/bin/pip /usr/bin/pip_backup 
		ln -sf /usr/bin/pip3.4 /usr/bin/pip
	fi
fi

tmp=`python -V 2>&1|awk '{print $2}'`
pVersion=${tmp:0:3}

Install_setuptools()
{
	if [ ! -f "/usr/bin/easy_install" ];then
		wget -O setuptools-33.1.1.zip $download_Url/install/src/setuptools-33.1.1.zip -T 10
		unzip setuptools-33.1.1.zip
		rm -f setuptools-33.1.1.zip
		cd setuptools-33.1.1
		python setup.py install
		cd ..
		rm -rf setuptools-33.1.1
	fi
	
	if [ ! -f "/usr/bin/easy_install" ];then
		echo '=================================================';
		echo -e "\033[31msetuptools installation failed. \033[0m";
		exit;
	fi
}

Install_pip()
{
	ispip=`pip -V |grep from`
	if [ "$ispip" == "" ];then
		if [ ! -f "/usr/bin/easy_install" ];then
			Install_setuptools
		fi
		wget -O pip-9.0.1.tar.gz $download_Url/install/src/pip-9.0.1.tar.gz -T 10
		tar xvf pip-9.0.1.tar.gz
		rm -f pip-9.0.1.tar.gz
		cd pip-9.0.1
		python setup.py install
		cd ..
		rm -rf pip-9.0.1
	fi
	ispip=`pip -V |grep from`
	if [ "$ispip" = "" ];then
		echo '=================================================';
		echo -e "\033[31m Python-pip installation failed. \033[0m";
		exit;
	fi
	
	pip install -U pip
}

Install_Pillow()
{
	isSetup=`python -m PIL 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		isFedora = `cat /etc/redhat-release |grep Fedora`
		if [ "$isFedora" != "" ];then
			pip install Pillow
			return;
		fi
		wget -O Pillow-3.2.0.zip $download_Url/install/src/Pillow-3.2.0.zip -T 10
		unzip Pillow-3.2.0.zip
		rm -f Pillow-3.2.0.zip
		cd Pillow-3.2.0
		python setup.py install
		cd ..
		rm -rf Pillow-3.2.0
	fi
	
	isSetup=`python -m PIL 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mPillow installation failed. \033[0m";
		exit;
	fi
}

Install_psutil()
{
	isSetup=`python -m psutil 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O psutil-5.2.2.tar.gz $download_Url/install/src/psutil-5.2.2.tar.gz -T 10
		tar xvf psutil-5.2.2.tar.gz
		rm -f psutil-5.2.2.tar.gz
		cd psutil-5.2.2
		python setup.py install
		cd ..
		rm -rf psutil-5.2.2
	fi
	isSetup=`python -m psutil 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mpsutil installation failed. \033[0m";
		exit;
	fi
}

Install_mysqldb()
{
	isSetup=`python -m MySQLdb 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O MySQL-python-1.2.5.zip $download_Url/install/src/MySQL-python-1.2.5.zip -T 10
		unzip MySQL-python-1.2.5.zip
		rm -f MySQL-python-1.2.5.zip
		cd MySQL-python-1.2.5
		python setup.py install
		cd ..
		rm -rf MySQL-python-1.2.5
	fi
}

Install_chardet()
{
	isSetup=`python -m chardet 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O chardet-2.3.0.tar.gz $download_Url/install/src/chardet-2.3.0.tar.gz -T 10
		tar xvf chardet-2.3.0.tar.gz
		rm -f chardet-2.3.0.tar.gz
		cd chardet-2.3.0
		python setup.py install
		cd ..
		rm -rf chardet-2.3.0
	fi	
	
	isSetup=`python -m chardet 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mchardet installation failed. \033[0m";
		exit;
	fi
}

Install_webpy()
{
	isSetup=`python -m web 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		wget -O web.py-0.38.tar.gz $download_Url/install/src/web.py-0.38.tar.gz -T 10
		tar xvf web.py-0.38.tar.gz
		rm -f web.py-0.38.tar.gz
		cd web.py-0.38
		python setup.py install
		cd ..
		rm -rf web.py-0.38
	fi
	
	isSetup=`python -m web 2>&1|grep package`
	if [ "$isSetup" = "" ];then
		echo '=================================================';
		echo -e "\033[31mweb.py installation failed. \033[0m";
		exit;
	fi
}


Install_setuptools
Install_pip

if [ "${download_Url}" = "$CN" ]; then
	if [ ! -d "/root/.pip" ];then
		mkdir ~/.pip
	fi
    cat > ~/.pip/pip.conf <<EOF
[global]
index-url = https://pypi.doubanio.com/simple/

[install]
trusted-host=pypi.doubanio.com
EOF
fi

isPsutil=`python -m psutil 2>&1|grep package`
if [ "$isPsutil" != "" ];then
	psutil_version=`python -c 'import psutil;print psutil.__version__;' |grep '5.'` 
	if [ "$psutil_version" = '' ];then
		pip uninstall psutil -y 
	fi
fi
yum install libffi-devel -y
pip install --upgrade setuptools
pip install -U pip
pip install itsdangerous==0.24
pip install paramiko==2.0.2
pip install flask-socketio==3.0.2
pip install python-socketio==2.1.2
for p_name in psutil chardet virtualenv Flask Flask-Session Flask-SocketIO flask-sqlalchemy Pillow gunicorn gevent-websocket;
do
	pip install ${p_name}
done

pip install psutil chardet virtualenv Flask Flask-Session Flask-SocketIO flask-sqlalchemy Pillow gunicorn gevent-websocket paramiko
Install_Pillow
Install_psutil

pip install gunicorn

if [  -f /www/server/mysql/bin/mysql ]; then
	pip install mysql-python
	Install_mysqldb
fi
Install_chardet

mkdir -p $setup_path/server/panel/logs
mkdir -p $setup_path/server/panel/vhost/apache
mkdir -p $setup_path/server/panel/vhost/nginx
mkdir -p $setup_path/server/panel/vhost/rewrite


if [ -f '/etc/init.d/bt' ];then
	/etc/init.d/bt stop
fi

mkdir -p /www/server
mkdir -p /www/wwwroot
mkdir -p /www/wwwlogs
mkdir -p /www/backup/database
mkdir -p /www/backup/site

if [ ! -f "/usr/bin/unzip" ];then
	#rm -f /etc/yum.repos.d/epel.repo
	yum install unzip -y
fi
wget -O panel.zip $download_Url/install/src/panel6.zip -T 10
wget -O /etc/init.d/bt $download_Url/install/src/bt6.init -T 10
if [ -f "$setup_path/server/panel/data/default.db" ];then
	if [ -d "/$setup_path/server/panel/old_data" ];then
		rm -rf $setup_path/server/panel/old_data
	fi
	mkdir -p $setup_path/server/panel/old_data
	mv -f $setup_path/server/panel/data/default.db $setup_path/server/panel/old_data/default.db
	mv -f $setup_path/server/panel/data/system.db $setup_path/server/panel/old_data/system.db
	mv -f $setup_path/server/panel/data/port.pl $setup_path/server/panel/old_data/port.pl
	mv -f $setup_path/server/panel/data/admin_path.pl $setup_path/server/panel/old_data/admin_path.pl
fi

unzip -o panel.zip -d $setup_path/server/ > /dev/null

if [ -d "$setup_path/server/panel/old_data" ];then
	mv -f $setup_path/server/panel/old_data/default.db $setup_path/server/panel/data/default.db
	mv -f $setup_path/server/panel/old_data/system.db $setup_path/server/panel/data/system.db
	mv -f $setup_path/server/panel/old_data/port.pl $setup_path/server/panel/data/port.pl
	mv -f $setup_path/server/panel/old_data/admin_path.pl $setup_path/server/panel/data/admin_path.pl
	if [ -d "/$setup_path/server/panel/old_data" ];then
		rm -rf $setup_path/server/panel/old_data
	fi
fi

rm -f panel.zip

if [ ! -f $setup_path/server/panel/tools.py ];then
	echo -e "\033[31mERROR: Failed to download, please try again!\033[0m";
	echo '============================================'
	exit;
fi

rm -f $setup_path/server/panel/class/*.pyc
rm -f $setup_path/server/panel/*.pyc



chmod +x /etc/init.d/bt
chkconfig --add bt
chkconfig --level 2345 bt on
chmod -R 600 $setup_path/server/panel
chmod -R +x $setup_path/server/panel/script
ln -sf /etc/init.d/bt /usr/bin/bt
echo "$port" > $setup_path/server/panel/data/port.pl
/etc/init.d/bt start

password=`cat /etc/passwd | head -c 16 | md5sum | head -c 8`
sleep 1
admin_auth='/www/server/panel/data/admin_path.pl'
if [ ! -f $admin_auth ];then
	auth_path=`cat /etc/passwd | head -c 16 | md5sum | head -c 8`
	echo "/$auth_path" > $admin_auth
fi
auth_path=`cat $admin_auth`
cd $setup_path/server/panel/
python -m py_compile tools.py
username=tgbaota
cd ~
echo "$password" > $setup_path/server/panel/default.pl
chmod 600 $setup_path/server/panel/default.pl
/etc/init.d/bt restart
sleep 3
isStart=`ps aux |grep 'gunicorn'|grep -v grep|awk '{print $2}'`
userbt(){
bt  1>/dev/null  <<EOF
6
tgbaota
EOF
sleep 2
newpassword=$(cat /www/server/panel/default.pl)
cd /www/server/panel && python tools.pyc panel $newpassword   1>/dev/null
}
btport(){
bt  1>/dev/null  <<EOF
11
EOF
sleep 3
}

if [ "$isStart" == '' ];then
	echo -e "\033[31mERROR: The BT-Panel service startup failed.\033[0m";
	echo '============================================'
	exit;
fi

if [ ! -f /root/.ssh/authorized_keys ] || [ ! -f /root/.ssh/id_rsa ];then
	if [ -f /root/.ssh/id_rsa ];then
		rm -f /root/.ssh/id_rsa /root/.ssh/id_rsa.pub
	fi
	ssh-keygen -q -t rsa -P "" -f /root/.ssh/id_rsa
fi
cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

if [ -f "/etc/init.d/iptables" ];then
	sshPort=`cat /etc/ssh/sshd_config | grep 'Port ' | grep -oE [0-9] | tr -d '\n'`
	if [ "${sshPort}" != "22" ]; then
		iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport $sshPort -j ACCEPT
	fi
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 20 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport $port -j ACCEPT
	iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport 39000:40000 -j ACCEPT
	#iptables -I INPUT -p tcp -m state --state NEW -m udp --dport 39000:40000 -j ACCEPT
	iptables -A INPUT -p icmp --icmp-type any -j ACCEPT
	iptables -A INPUT -s localhost -d localhost -j ACCEPT
	iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
	iptables -P INPUT DROP
	service iptables save
	sed -i "s#IPTABLES_MODULES=\"\"#IPTABLES_MODULES=\"ip_conntrack_netbios_ns ip_conntrack_ftp ip_nat_ftp\"#" /etc/sysconfig/iptables-config

	iptables_status=`service iptables status | grep 'not running'`
	if [ "${iptables_status}" == '' ];then
		service iptables restart
	fi
fi

if [ "${isVersion}" == '' ];then
	if [ ! -f "/etc/init.d/iptables" ];then
		sshPort=`cat /etc/ssh/sshd_config | grep 'Port ' | grep -oE [0-9] | tr -d '\n'`
		yum install firewalld -y
		systemctl restart firewalld
		firewall-cmd --set-default-zone=public > /dev/null 2>&1
		if [ "${sshPort}" != "22" ]; then
			firewall-cmd --permanent --zone=public --add-port=$sshPort/tcp > /dev/null 2>&1
		fi
		firewall-cmd --permanent --zone=public --add-port=20/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=21/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=22/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=$port/tcp > /dev/null 2>&1
		firewall-cmd --permanent --zone=public --add-port=39000-40000/tcp > /dev/null 2>&1
		#firewall-cmd --permanent --zone=public --add-port=39000-40000/udp > /dev/null 2>&1
		firewall-cmd --reload
	fi
fi

pip install psutil chardet psutil virtualenv cryptography==2.1 > /dev/null 2>&1

if [ ! -d '/etc/letsencrypt' ];then
	yum install epel-release -y

	if [ "${country}" = "CN" ]; then
		isC7=`cat /etc/redhat-release |grep ' 7.'`
		if [ "${isC7}" == "" ];then
			wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
		else
			wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
		fi
	fi
	mkdir -p /var/spool/cron
	if [ ! -f '/var/spool/cron/root' ];then
		echo '' > /var/spool/cron/root
		chmod 600 /var/spool/cron/root
	fi
fi

wget -O acme_install.sh $download_Url/install/acme_install.sh
nohup bash acme_install.sh &> /dev/null &
sleep 1
rm -f acme_install.sh

address=""
address=`curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress`
if [ "$address" == '0.0.0.0' ] || [ "$address" == '' ];then
	isHosts=`cat /etc/hosts|grep 'www.bt.cn'`
	if [ "$isHosts" == '' ];then
		echo "" >> /etc/hosts
		echo "125.88.182.170 www.bt.cn" >> /etc/hosts
		address=`curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress`
		if [ "$address" == '' ];then
			sed -i "/bt.cn/d" /etc/hosts
		fi
	fi
fi

ipCheck=`python -c "import re; print(re.match('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$','$address'))"`
if [ "$ipCheck" == "None" ];then
	address="SERVER_IP"
fi

if [ "$address" != "SERVER_IP" ];then
	echo "$address" > $setup_path/server/panel/data/iplist.txt
fi

curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/SetupCount?type=Linux\&o=$1 > /dev/null 2>&1
if [ "$1" != "" ];then
	echo $1 > /www/server/panel/data/o.pl
	cd /www/server/panel
	python tools.py o
fi
echo /www > /var/bt_setupPath.conf
/etc/init.d/bt start
userbt
btport
echo -e "=================================================================="
echo -e "\033[32mCongratulations! Installed successfully!\033[0m"
echo -e "=================================================================="
echo  "Bt-Panel: http://$address:$port"  
echo -e "username: $username"		
echo -e "password: $password"		
echo -e "\033[33mWarning:\033[0m"
echo -e "\033[33mIf you cannot access the panel, \033[0m"
echo -e "\033[33mrelease the following port (2222|888|80|443|20|21) in the security group\033[0m"
echo -e "=================================================================="

endTime=`date +%s`
((outTime=($endTime-$startTime)/60))
echo -e "Time consumed:\033[32m $outTime \033[0mMinute!"

	read -p "是否重启主机 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		reboot
	else
		start_menu
	fi

#done
clear ;
check_port() {
        echo "正在检测Zabbix服务..."
        netstat -tlpn | grep "\b$1\b"
}
if check_port 10050
then
        echo "Zabbix 已成功启动！"
else
        echo "Zabbix 未启动成功！"
        DATE_N=`date "+%Y-%m%d %H:%M:%S"`
        echo "时间：${DATE_N}" >> zabbix.log #记录死亡日志
fi
}

#模板主机初始化
init_MB() {
firewall-cmd --permanent --zone=public --add-port=2222/tcp > /dev/null 2>&1
firewall-cmd --reload   > /dev/null 2>&1
echo '0 * * * *  root  /usr/sbin/ntpdate -u pool.ntp.org &>/dev/null 2>&1 || ntpdate -u time.nist.gov &>/dev/null 2>&1 || ntpdate -u  ntp1.aliyun.com &>/dev/null 2>&1  || ntpdate -u  ntp2.aliyun.com &>/dev/null 2>&1 || ntpdate -u  ntp3.aliyun.com &>/dev/null 2>&1 || ntpdate -u  ntp4.aliyun.com  &>/dev/null 2>&1 ' >> /etc/crontab
systemctl restart crond ; systemctl enable crond 
read -p "Please enter BT user password:" btpasswd
read -p "Please enter root user password:" rootpasswd
btpasswd(){
btpasswd=$btpasswd
rootpasswd=$rootpasswd
#修改bt密码
bt  1>/dev/null  <<EOF
5
$btpasswd
EOF
}
btpasswd
#修改root密码
echo "$rootpasswd" | passwd --stdin root
#创建lottery用户
Create_lottery

}

#数据库安装zabbix
Mysql_Zabbix() {
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
RLS=`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`
#read -p "请输入盘口编号:" ZabbixNnam
#HOSTNAME=$ZabbixNnam-`hostname`

if [ $(id -u) != "0" ]; then
                echo "Error: Please use root user login"
    exit 1
fi

if [ -s /etc/selinux/config ]; then
        sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
        setenforce 0
fi

#read -p "Enter zabbix server ip address(default：3.0.159.208):" ZSERVERIP
        ZSERVERIP=${ZSERVERIP:=3.0.159.208}
if [ "$RLS" = "6" ]; then
                rpm -i https://repo.zabbix.com/zabbix/4.4/rhel/6/x86_64/zabbix-release-4.4-1.el6.noarch.rpm
        else
                rpm -i https://repo.zabbix.com/zabbix/4.4/rhel/7/x86_64/zabbix-release-4.4-1.el7.noarch.rpm
fi
yum install -y zabbix-agent net-tools
        sed -i "s/^Server=127.0.0.1/Server=$ZSERVERIP/g" /etc/zabbix/zabbix_agentd.conf
        sed -i "s/^ServerActive=127.0.0.1/ServerActive=$ZSERVERIP/g" /etc/zabbix/zabbix_agentd.conf
        sed -i "s/^Hostname=Zabbix server/Hostname=$HOSTNAME/g" /etc/zabbix/zabbix_agentd.conf
	read -p "请输入盘口编号:" ZabbixNnam
	HOSTNAME=$ZabbixNnam-`hostname`
        sed -i "s/^Hostname=`hostname`/Hostname=$HOSTNAME/g" /etc/zabbix/zabbix_agentd.conf
if [ "$RLS" = "6" ]; then
        /sbin/iptables -I INPUT -s $ZSERVERIP -j ACCEPT
        /sbin/iptables -I INPUT -s $ZSERVERIP -p tcp --dport 10050 -j ACCEPT
        service iptables save && service iptables restart && service zabbix-agent start && chkconfig zabbix-agent on
        else
        firewall-cmd --zone=public --add-port=10050/tcp --permanent
        systemctl restart zabbix-agent.service && systemctl enable zabbix-agent.service && firewall-cmd --reload
fi

#done
clear ;
check_port() {
        echo "正在检测Zabbix服务..."
	cat /etc/zabbix/zabbix_agentd.conf  |grep Hostname= |awk 'NR==2{print}'
        netstat -tlpn | grep "\b$1\b"
}
if check_port 10050
then
        echo "Zabbix 已成功启动！"
else
        echo "Zabbix 未启动成功！"
        DATE_N=`date "+%Y-%m%d %H:%M:%S"`
        echo "时间：${DATE_N}" >> zabbix.log #记录死亡日志
fi

	read -p "是否返回管理脚本菜单 ? [Y/n] :" yn
	[ -z "${yn}" ] && yn="y"
	if [[ $yn == [Yy] ]]; then
		start_menu
	else
		exit 1
	fi
}

#开始菜单
start_menu(){
clear
echo && echo -e " TG平台 一键安装管理脚本 
 
————————————系统管理————————————
 ${Green_font_prefix}0.${Font_color_suffix} 安装宝塔
 ${Green_font_prefix}1.${Font_color_suffix} 安装 Verynginx
 ${Green_font_prefix}2.${Font_color_suffix} 系统初始化
 ${Green_font_prefix}3.${Font_color_suffix} 优化系统配置
 ${Green_font_prefix}4.${Font_color_suffix} 安装 BBR/BBR魔改版内核
 ${Green_font_prefix}5.${Font_color_suffix} 使用BBR魔改版加速
 ${Green_font_prefix}6.${Font_color_suffix} 添加lottery用户 
 ${Green_font_prefix}7.${Font_color_suffix} 安装 Zabbix客户端
 ${Green_font_prefix}8.${Font_color_suffix} 数据库基准测试
————————————杂项管理————————————
 ${Green_font_prefix}9.${Font_color_suffix} 卸载全部加速
 ${Green_font_prefix}10.${Font_color_suffix} 重启服务器
 ${Green_font_prefix}11.${Font_color_suffix} 添加开机启动程序（consul、api、web、job）
 ${Green_font_prefix}12.${Font_color_suffix} 一键初始化（0-1-2-3-4-5）
 ${Green_font_prefix}13.${Font_color_suffix} 检测服务是否安装成功
 ${Green_font_prefix}14.${Font_color_suffix} 服务器初始化（模板主机）
 ${Green_font_prefix}15.${Font_color_suffix} 退出脚本
 ${Green_font_prefix}16.${Font_color_suffix} 数据库安装Zabbix客户端
————————————————————————————————" && echo

	check_status
	if [[ ${kernel_status} == "noinstall" ]]; then
		echo -e " 当前状态: ${Green_font_prefix}未安装${Font_color_suffix} 加速内核 ${Red_font_prefix}请先安装内核${Font_color_suffix}"
	else
		echo -e " 当前状态: ${Green_font_prefix}已安装${Font_color_suffix} ${_font_prefix}${kernel_status}${Font_color_suffix} 加速内核 , ${Green_font_prefix}${run_status}${Font_color_suffix}"
		
	fi
echo
read -p " 请输入数字 [0-16]:" num
case "$num" in
	0)
	install_BT 
	;;
	1)
	Verynginx_install
	;;
	2)
	system_init
	;;
	3)
	optimizing_system
	;;
        4)
	check_sys_bbr
	;;
	5)
	startbbr
	;;
	6)
	Create_lottery
	;;
	7)
	install_zabbixClient
	;;
	8)
	Mysql_test
	;;
	9)
	remove_all
	;;
	10)
	reboot
	;;
	11)
	start_java
	;;
	12)
	install_all  
	;;
	13)
	Testing 
	;;
	14)
	init_MB
	;;
	15)
	exit 1
	;;
	16)
	Mysql_Zabbix
	;;
	*)
	clear
	echo -e "${Error}:请输入正确数字 [0-16]"
	sleep 1s
	start_menu
	;;
esac
}
#############内核管理组件#############

#删除多余内核
detele_kernel(){
	if [[ "${release}" == "centos" ]]; then
		rpm_total=`rpm -qa | grep kernel | grep -v "${kernel_version}" | grep -v "noarch" | wc -l`
		if [ "${rpm_total}" > "1" ]; then
			echo -e "检测到 ${rpm_total} 个其余内核，开始卸载..."
			for((integer = 1; integer <= ${rpm_total}; integer++)); do
				rpm_del=`rpm -qa | grep kernel | grep -v "${kernel_version}" | grep -v "noarch" | head -${integer}`
				echo -e "开始卸载 ${rpm_del} 内核..."
				rpm --nodeps -e ${rpm_del}
				echo -e "卸载 ${rpm_del} 内核卸载完成，继续..."
			done
			echo --nodeps -e "内核卸载完毕，继续..."
		else
			echo -e " 检测到 内核 数量不正确，请检查 !" && exit 1
		fi
	elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then
		deb_total=`dpkg -l | grep linux-image | awk '{print $2}' | grep -v "${kernel_version}" | wc -l`
		if [ "${deb_total}" > "1" ]; then
			echo -e "检测到 ${deb_total} 个其余内核，开始卸载..."
			for((integer = 1; integer <= ${deb_total}; integer++)); do
				deb_del=`dpkg -l|grep linux-image | awk '{print $2}' | grep -v "${kernel_version}" | head -${integer}`
				echo -e "开始卸载 ${deb_del} 内核..."
				apt-get purge -y ${deb_del}
				echo -e "卸载 ${deb_del} 内核卸载完成，继续..."
			done
			echo -e "内核卸载完毕，继续..."
		else
			echo -e " 检测到 内核 数量不正确，请检查 !" && exit 1
		fi
	fi
}

#更新引导
BBR_grub(){
	if [[ "${release}" == "centos" ]]; then
        if [[ ${version} = "6" ]]; then
            if [ ! -f "/boot/grub/grub.conf" ]; then
                echo -e "${Error} /boot/grub/grub.conf 找不到，请检查."
                exit 1
            fi
            sed -i 's/^default=.*/default=0/g' /boot/grub/grub.conf
        elif [[ ${version} = "7" ]]; then
            if [ ! -f "/boot/grub2/grub.cfg" ]; then
                echo -e "${Error} /boot/grub2/grub.cfg 找不到，请检查."
                exit 1
            fi
            grub2-set-default 0
        fi
    elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then
        /usr/sbin/update-grub
    fi
}

#############内核管理组件#############



#############系统检测组件#############

#检查系统
check_sys(){
	if [[ -f /etc/redhat-release ]]; then
		release="centos"
	elif cat /etc/issue | grep -q -E -i "debian"; then
		release="debian"
	elif cat /etc/issue | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
	elif cat /proc/version | grep -q -E -i "debian"; then
		release="debian"
	elif cat /proc/version | grep -q -E -i "ubuntu"; then
		release="ubuntu"
	elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then
		release="centos"
    fi
   #bash <(curl -s http://dl.tg9.me/openresty/conf/nginx.tar.gz)
}

#检查Linux版本
check_version(){
	if [[ -s /etc/redhat-release ]]; then
		version=`grep -oE  "[0-9.]+" /etc/redhat-release | cut -d . -f 1`
	else
		version=`grep -oE  "[0-9.]+" /etc/issue | cut -d . -f 1`
	fi
	bit=`uname -m`
	if [[ ${bit} = "x86_64" ]]; then
		bit="x64"
	else
		bit="x32"
	fi
}

#检查安装bbr的系统要求
check_sys_bbr(){
	check_version
	if [[ "${release}" == "centos" ]]; then
		if [[ ${version} -ge "6" ]]; then
			installbbr
		else
			echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
		fi
	elif [[ "${release}" == "debian" ]]; then
		if [[ ${version} -ge "8" ]]; then
			installbbr
		else
			echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
		fi
	elif [[ "${release}" == "ubuntu" ]]; then
		if [[ ${version} -ge "14" ]]; then
			installbbr
		else
			echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
		fi
	else
		echo -e "${Error} BBR内核不支持当前系统 ${release} ${version} ${bit} !" && exit 1
	fi
}

check_status(){
	kernel_version=`uname -r | awk -F "-" '{print $1}'`
	kernel_version_full=`uname -r`
	if [[ ${kernel_version_full} = "4.14.91-bbrplus" ]]; then
		kernel_status="BBRplus"
	elif [[ ${kernel_version} = "3.10.0" || ${kernel_version} = "3.16.0" || ${kernel_version} = "3.2.0" || ${kernel_version} = "4.4.0" || ${kernel_version} = "3.13.0"  || ${kernel_version} = "2.6.32" ]]; then
		kernel_status="Lotserver"
	elif [[ `echo ${kernel_version} | awk -F'.' '{print $1}'` == "4" ]] && [[ `echo ${kernel_version} | awk -F'.' '{print $2}'` -ge 9 ]]; then
		kernel_status="BBR"
	else 
		kernel_status="noinstall"
	fi

	if [[ ${kernel_status} == "Lotserver" ]]; then
		if [[ -e /appex/bin/serverSpeeder.sh ]]; then
			run_status=`bash /appex/bin/serverSpeeder.sh status | grep "ServerSpeeder" | awk  '{print $3}'`
			if [[ ${run_status} = "running!" ]]; then
				run_status="启动成功"
			else 
				run_status="启动失败"
			fi
		else 
			run_status="未安装加速模块"
		fi
	elif [[ ${kernel_status} == "BBR" ]]; then
		run_status=`grep "net.ipv4.tcp_congestion_control" /etc/sysctl.conf | awk -F "=" '{print $2}'`
		if [[ ${run_status} == "bbr" ]]; then
			run_status=`lsmod | grep "bbr" | awk '{print $1}'`
			if [[ ${run_status} == "tcp_bbr" ]]; then
				run_status="BBR启动成功"
			else 
				run_status="BBR启动失败"
			fi
		elif [[ ${run_status} == "tsunami" ]]; then
			run_status=`lsmod | grep "tsunami" | awk '{print $1}'`
			if [[ ${run_status} == "tcp_tsunami" ]]; then
				run_status="BBR魔改版启动成功"
			else 
				run_status="BBR魔改版启动失败"
			fi
		elif [[ ${run_status} == "nanqinlang" ]]; then
			run_status=`lsmod | grep "nanqinlang" | awk '{print $1}'`
			if [[ ${run_status} == "tcp_nanqinlang" ]]; then
				run_status="暴力BBR魔改版启动成功"
			else 
				run_status="暴力BBR魔改版启动失败"
			fi
		else 
			run_status="未安装加速模块"
		fi
	elif [[ ${kernel_status} == "BBRplus" ]]; then
		run_status=`grep "net.ipv4.tcp_congestion_control" /etc/sysctl.conf | awk -F "=" '{print $2}'`
		if [[ ${run_status} == "bbrplus" ]]; then
			run_status=`lsmod | grep "bbrplus" | awk '{print $1}'`
			if [[ ${run_status} == "tcp_bbrplus" ]]; then
				run_status="BBRplus启动成功"
			else 
				run_status="BBRplus启动失败"
			fi
		else 
			run_status="未安装加速模块"
		fi
	fi
}

#############系统检测组件#############
check_sys
check_version
[[ ${release} != "debian" ]] && [[ ${release} != "ubuntu" ]] && [[ ${release} != "centos" ]] && echo -e "${Error} 本脚本不支持当前系统 ${release} !" && exit 1
start_menu






