#!/bin/bash

# Minimal Load Testing Setup for wrk

set -e  # Exit on any error

echo "=== Minimal Load Testing Setup ==="

# Update system and install wrk
echo "Installing wrk..."
sudo apt-get update
sudo apt-get install -y wrk

# Increase file descriptor limits
echo "Setting file descriptor limits..."
echo "* soft nofile 65536" | sudo tee -a /etc/security/limits.conf
echo "* hard nofile 65536" | sudo tee -a /etc/security/limits.conf

# Network tuning for load testing
echo "Applying network tuning..."
sudo tee -a /etc/sysctl.conf << EOF

# Load testing network optimizations
net.core.somaxconn = 65536
net.core.netdev_max_backlog = 5000
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_congestion_control = bbr
net.ipv4.tcp_max_syn_backlog = 30000
net.ipv4.tcp_max_tw_buckets = 2000000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15
EOF

# Apply sysctl changes
sudo sysctl -p

# Set ulimit for current session
ulimit -n 65536

# Add to bashrc for future sessions
echo "ulimit -n 65536" >> ~/.bashrc

echo "=== Setup Complete ==="
echo "wrk version: $(wrk --version)"
echo "Current file descriptor limit: $(ulimit -n)"
echo ""
echo "IMPORTANT: Start new shell session or reboot for all limits to take effect"