#!/usr/bin/env bash

# 获取系统架构和内存信息
arch=$(getconf LONG_BIT)                       # 系统位数
memory_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}') # 总内存 (KB)
memory_mb=$(expr $memory_kb / 1024)            # 转换为 MB
memory_gb=$(expr $memory_mb / 1024)            # 转换为 GB
a=$(expr $arch / 32)                           # 系统位数比例因子

# 动态计算参数
fs_file_max=$(expr $memory_mb \* 256)          # 文件描述符限制
conntrack_max=$(expr $memory_mb / 16 / $a)     # Conntrack 最大连接数
buckets=$(expr $conntrack_max / 4)             # Conntrack 哈希桶大小
rmem_max=$(expr $memory_mb \* 1024 \* 4)       # 网络接收缓冲区最大值
wmem_max=$(expr $memory_mb \* 1024 \* 4)       # 网络发送缓冲区最大值
netdev_max_backlog=$(expr $memory_mb \* 128)   # 网络接口队列长度
somaxconn=$(expr $memory_mb \* 16)             # TCP 侦听队列长度
tcp_max_tw_buckets=$(expr $memory_mb \* 4)     # TIME-WAIT 缓存连接数量

# 输出颜色设置
echo=echo
for cmd in echo /bin/echo; do
    $cmd >/dev/null 2>&1 || continue

    if ! $cmd -e "" | grep -qE '^-e'; then
        echo=$cmd
        break
    fi
done

CSI=$($echo -e "\033[")
CEND="${CSI}0m"
CDGREEN="${CSI}32m"
CRED="${CSI}1;31m"
CGREEN="${CSI}1;32m"
CYELLOW="${CSI}1;33m"
CBLUE="${CSI}1;34m"
CMAGENTA="${CSI}1;35m"
CCYAN="${CSI}1;36m"

OUT_ALERT() {
    echo -e "${CYELLOW}$1${CEND}"
}

OUT_ERROR() {
    echo -e "${CRED}$1${CEND}"
}

OUT_INFO() {
    echo -e "${CCYAN}$1${CEND}"
}

# 检测系统发行版
if [[ -f /etc/redhat-release ]]; then
    release="centos"
elif cat /etc/issue | grep -q -E -i "debian|raspbian"; 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 "raspbian|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"
else
    OUT_ERROR "[错误] 不支持的操作系统！"
    exit 1
fi

# 更新系统
OUT_ALERT "[信息] 更新系统中！"
if [[ ${release} == "centos" ]]; then
    yum makecache
    yum install epel-release -y
    yum update -y
else
    apt update -y
    apt autoremove --purge -y
fi

# 配置性能参数
OUT_ALERT "[信息] 优化参数中！"
echo "ip_conntrack" | sudo tee -a /etc/modules
modprobe ip_conntrack
chattr -i /etc/sysctl.conf
cat > /etc/sysctl.conf << EOF
vm.swappiness = 0
fs.file-max = $fs_file_max
net.core.rmem_max = $rmem_max
net.core.wmem_max = $wmem_max
net.core.netdev_max_backlog = $netdev_max_backlog
net.core.default_qdisc = fq_pie
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.lo.arp_announce = 2
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.default.arp_announce = 2
net.ipv4.ip_forward = 1
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.neigh.default.gc_stale_time = 30
net.ipv4.tcp_ecn = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_low_latency = 1
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_keepalive_time = 10
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_sack = 1
net.ipv4.tcp_fack = 1
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_synack_retries = 3
net.ipv4.tcp_max_syn_backlog = 16384
net.core.somaxconn = $somaxconn
net.ipv4.tcp_abort_on_overflow = 1
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_max_tw_buckets = $tcp_max_tw_buckets
net.ipv4.tcp_fastopen = 3
net.ipv4.tcp_mtu_probing = 1
net.ipv4.tcp_rmem = 4096 87380 $rmem_max
net.ipv4.tcp_wmem = 4096 65536 $wmem_max
net.ipv4.tcp_congestion_control = bbr
net.ipv6.conf.all.forwarding = 1
net.ipv6.conf.default.forwarding = 1
net.nf_conntrack_max = $conntrack_max
net.netfilter.nf_conntrack_max = $conntrack_max
net.netfilter.nf_conntrack_buckets = $buckets
net.netfilter.nf_conntrack_generic_timeout = 10
net.netfilter.nf_conntrack_icmp_timeout = 2
net.netfilter.nf_conntrack_tcp_max_retrans = 2
net.netfilter.nf_conntrack_tcp_timeout_close = 2
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 2
net.netfilter.nf_conntrack_tcp_timeout_established = 300
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 2
net.netfilter.nf_conntrack_tcp_timeout_last_ack = 2
net.netfilter.nf_conntrack_tcp_timeout_max_retrans = 2
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 2
net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 2
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 60
net.netfilter.nf_conntrack_tcp_timeout_unacknowledged = 2
net.netfilter.nf_conntrack_udp_timeout = 2
net.netfilter.nf_conntrack_udp_timeout_stream = 30
EOF

# 配置文件句柄和进程限制
cat > /etc/security/limits.conf << EOF
* soft nofile 512000
* hard nofile 512000
* soft nproc 512000
* hard nproc 512000
root soft nofile 512000
root hard nofile 512000
root soft nproc 512000
root hard nproc 512000
EOF

# 配置 systemd 日志限制
cat > /etc/systemd/journald.conf << EOF
[Journal]
SystemMaxUse=384M
SystemMaxFileSize=128M
ForwardToSyslog=no
EOF

# 应用优化参数
sysctl -p
sudo rm -rf /root/optimize.sh && history -c
OUT_INFO "[信息] 优化完毕！"
exit 0