#!/bin/bash
# Auto optimize sysctl based on system hardware
# Works on Ubuntu/Debian + CentOS/RHEL
# Author: ChatGPT

set -e

# Backup sysctl.conf
BACKUP_FILE="/etc/sysctl.conf.bak_$(date +%F_%H%M%S)"
SYSCTL_TMP="/etc/sysctl.conf.new"

echo "[*] Backup sysctl.conf -> $BACKUP_FILE"
cp /etc/sysctl.conf "$BACKUP_FILE" 2>/dev/null || touch "$BACKUP_FILE"

# Detect distro
if [ -f /etc/os-release ]; then
    . /etc/os-release
    DISTRO=$ID
else
    DISTRO=$(uname -s)
fi

# Detect hardware info
CPU_CORES=$(nproc)
TOTAL_RAM_MB=$(free -m | awk '/^Mem:/{print $2}')
TOTAL_RAM_GB=$((TOTAL_RAM_MB/1024))
KERNEL=$(uname -r)
NIC_COUNT=$(ls /sys/class/net | grep -Ev "lo|docker|veth" | wc -l)

echo "[*] Distro: $DISTRO"
echo "[*] Detected: $CPU_CORES cores, $TOTAL_RAM_GB GB RAM, $NIC_COUNT NIC, kernel $KERNEL"

# Generate sysctl config
cat > "$SYSCTL_TMP" <<EOF
# Optimized sysctl.conf generated on $(date)
# CPU: $CPU_CORES cores, RAM: ${TOTAL_RAM_GB}GB, NIC: $NIC_COUNT, Distro: $DISTRO

# --- Network tuning ---
net.core.somaxconn = 65535
net.core.netdev_max_backlog = $((CPU_CORES * 2048))
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_max_syn_backlog = $((CPU_CORES * 8192))
net.ipv4.tcp_tw_reuse = 1
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.tcp_syncookies = 1

# --- Memory tuning ---
vm.swappiness = 10
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
vm.overcommit_memory = 1

# --- File system ---
fs.file-max = $((CPU_CORES * 200000))

# --- Network security ---
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
EOF

echo "[*] Apply new sysctl config"
cp "$SYSCTL_TMP" /etc/sysctl.conf
sysctl -p /etc/sysctl.conf

echo "[+] Optimization applied successfully!"

