#!/bin/bash
# tune_os.sh
# Production-Grade OS Tuning for 4-Core 8GB RAM host running Caddy + Node + PHP + MySQL stack

set -e

echo "=== Starting Linux Host OS Performance Tuning ==="

# 1. Install Debugging Tools
echo "Installing debugging and diagnostics tools..."
sudo apt-get update
sudo apt-get install -y htop iotop nload dstat sysstat

# 2. Swap Tuning (8 GB Swap, Swappiness = 10, Cache Pressure = 50)
echo "Optimizing Swap settings..."
sudo swapoff -a || true
if [ -f /swapfile ]; then
    echo "Deleting old swapfile..."
    sudo rm -f /swapfile
fi

sudo fallocate -l 8G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# Ensure it's in /etc/fstab
if ! grep -q "/swapfile" /etc/fstab; then
    echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
fi

# Set swappiness and cache pressure persistently
echo "Configuring swappiness and virtual memory cache pressure..."
sudo sysctl vm.swappiness=10
sudo sysctl vm.vfs_cache_pressure=50

# 3. File Descriptors (Increase limits)
echo "Configuring file descriptor limits..."
sudo sysctl fs.file-max=2097152

if ! grep -q "nofile 262144" /etc/security/limits.conf; then
    echo "* soft nofile 262144" | sudo tee -a /etc/security/limits.conf
    echo "* hard nofile 262144" | sudo tee -a /etc/security/limits.conf
    echo "root soft nofile 262144" | sudo tee -a /etc/security/limits.conf
    echo "root hard nofile 262144" | sudo tee -a /etc/security/limits.conf
fi

# 4. Kernel Network Stack Tuning
echo "Tuning TCP/IP network queue backlogs..."
sysctl_config="/etc/sysctl.d/99-performance-tuning.conf"
sudo tee "$sysctl_config" <<EOF
# Increase max backlog queue size
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 8192
net.core.netdev_max_backlog = 16384

# Expand local port range for outgoing proxy sockets
net.ipv4.ip_local_port_range = 1024 65000

# Enable rapid recycling of TIME_WAIT sockets
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15

# Connection tracking limit
net.netfilter.nf_conntrack_max = 524288

# Memory limits for swap-discouraged performance
vm.swappiness = 10
vm.vfs_cache_pressure = 50
EOF

# Apply sysctl settings
sudo sysctl -p "$sysctl_config" || sudo sysctl --system

echo "=== Linux Host OS Performance Tuning Completed successfully ==="
echo "Note: Some changes like limits.conf require session logout/login or container restart to fully bind."
