#!/usr/bin/env bash
#https://www.modb.pro/db/43554
#https://www.cnblogs.com/zengkefu/p/5749009.html
#
# selinux and firewalld
setenforce 0 &&\
sed -ri 's/^(SELINUX=.*)/SELINUX=disabled/' /etc/selinux/config

# 179 2601 2605 10050 1066
yum install -y firewalld &&\
systemctl restart firewalld
firewall-cmd --permanent --zone=public --add-port=1066/tcp
firewall-cmd --reload
systemctl stop firewalld &&\
systemctl disable firewalld

# change sshd port
echo "Port 1066" >> /etc/ssh/sshd_config
systemctl restart sshd

# The maximum number of open system files
cat >> /etc/security/limits.conf <<AOF
* soft nofile 1000000
* hard nofile 1000000
AOF

# Linux custom kernel tuning
cat >> /etc/sysctl.d/Usercustomize.conf <<BOF
# 开启ipv4路由转发
net.ipv4.ip_forward = 1

#最大socket写buffer
net.core.wmem_max = 513920

#最大socket读buffer
net.core.rmem_max = 513920

#tcp写buffer
net.ipv4.tcp_wmem = 8760  256960  4088000

#tcp读buffer
net.ipv4.tcp_rmem = 8760  256960  4088000

#net.ipv4.tcp_mem [0] [1] [2] 单位: 页
#[0]:低于此值,TCP没有内存压力.
#[1]:在此值下,进入内存压力阶段.
#[2]:高于此值,TCP拒绝分配socket.
#net.ipv4.tcp_mem = 131072  262144  524288

#接收数据包的速率比内核处理这些包的速率快时，允许送到队列的数据包的最大数目。
net.core.netdev_max_backlog = 2000

#指定的最大accept队列backlog，当排队的请求连接大于该值时，后续进来的请求连接会被丢弃。
net.core.somaxconn = 2048

#每个端口的 TCP SYN队列长度的。超过则请求会被丢弃，前提是系统的syncookies功能被禁用
net.ipv4.tcp_max_syn_backlog = 4096

#SYN等待队列溢出时，启用cookies来处理，可防范少量SYN攻击
net.ipv4.tcp_syncookies = 1

#每个socket的副缓冲区大小
net.core.optmem_max = 81920

#TCP失败重传次数,默认值15
net.ipv4.tcp_retries2 = 5

#TCP连接在idle 1800s后,内核才发起probe.如果probe 3次(每次30秒)不成功,内核才认为该连接已失效
net.ipv4.tcp_keepalive_time = 1800
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3

#规定了tcp/udp可用的本地端口的范围,默认为32768到61000
net.ipv4.ip_local_port_range = 1024  65000

#允许将TIME-WAIT sockets重新用于新的TCP连接
net.ipv4.tcp_tw_reuse = 1

#表示SYN队列的长度，默认为1024
net.ipv4.tcp_max_syn_backlog = 8192

#表示系统同时保持TIME_WAIT套接字的最大数量
net.ipv4.tcp_max_tw_buckets = 5000
BOF
sysctl -p /etc/sysctl.d/Usercustomize.conf

### ins bbr 运行脚本化按任意键即可自动执行 安装完30秒内会自动重启，这里需要重启一下机器
yum -y install wget vim expect net-tools lrzsz bash-c*
cd /usr/local/src
wget --no-check-certificate http://itityunwei.cn/ss/bbr.sh
chmod +x bbr.sh
/usr/bin/expect <<COF
set timeout -1;
spawn ./bbr.sh;
expect "Press any key to start...or Press Ctrl+C to cancel"
send "do\r"
expect "*y/n*"
send "n\r"
expect eof
COF

if [[ $? -eq 0 ]];then
  reboot
else
   echo "Failed to install bbr, please check the log"; exit 1
fi
