#!/bin/bash

# Install resolvconf and configure DNS
apt update -y && apt upgrade -y
#apt install -y resolvconf

# Configure DNS nameservers
#echo -e "nameserver 1.1.1.1\nnameserver 1.0.0.1\nnameserver 2606:4700:4700::1111\nnameserver 2606:4700:4700::1001\nnameserver 2001:4860:4860::8888\nnameserver 2001:4860:4860::8844" > /etc/resolvconf/resolv.conf.d/head
#resolvconf -u
#systemctl enable resolvconf
#systemctl restart resolvconf

# Disable systemd-resolved service
#systemctl stop systemd-resolved
#systemctl disable systemd-resolved

# Set process limits
echo -e "* soft     nproc          1000000\n* hard     nproc          1000000\n* soft     nofile         1000000\n* hard     nofile         1000000\nroot soft  nproc          1000000\nroot hard  nproc          1000000\nroot soft  nofile         1000000\nroot hard  nofile         1000000" >> /etc/security/limits.conf

# Set ulimit
echo "ulimit -SHn 1000000" >> /etc/profile

# Update systemd limits
echo -e "DefaultLimitNOFILE=1000000\nDefaultLimitNPROC=1000000" >> /etc/systemd/system.conf
echo -e "DefaultLimitNOFILE=1000000\nDefaultLimitNPROC=1000000" >> /etc/systemd/user.conf
systemctl daemon-reload

# Set sysctl configurations
echo "" > /etc/sysctl.conf
echo -e "# TCP Congestion Control and Queue Discipline\nnet.ipv4.tcp_congestion_control = bbr\nnet.core.default_qdisc = cake\n\n# TCP Connection Handling\nnet.ipv4.tcp_syncookies = 1\nnet.ipv4.tcp_fin_timeout = 10\nnet.ipv4.tcp_tw_reuse = 1\nnet.ipv4.tcp_timestamps = 1\nnet.ipv4.ip_local_port_range = 1024 65535\nnet.ipv4.tcp_max_syn_backlog = 16384\nnet.ipv4.tcp_syn_retries = 3\nnet.ipv4.tcp_synack_retries = 3\nnet.ipv4.tcp_keepalive_time = 300\nnet.ipv4.tcp_no_metrics_save = 1\nnet.ipv4.tcp_fastopen = 3\nnet.ipv4.tcp_reordering = 3\nnet.ipv4.tcp_retries2 = 8\nnet.ipv4.tcp_ecn = 2\nnet.ipv4.tcp_low_latency = 1\n\n# File Descriptor Limits\nfs.file-max = 10000000\nfs.nr_open = 10000000\nfs.inotify.max_user_instances = 8192\n\n# Network Buffer Sizes\nnet.core.somaxconn = 32768\nnet.core.netdev_max_backlog = 32768\nnet.core.rmem_max = 16777216\nnet.core.wmem_max = 16777216\nnet.ipv4.tcp_rmem = 4096 87380 16777216\nnet.ipv4.tcp_wmem = 4096 16384 16777216\n\n# Connection Tracking\nnet.netfilter.nf_conntrack_max = 10485760\nnet.netfilter.nf_conntrack_tcp_timeout_fin_wait = 30\nnet.netfilter.nf_conntrack_tcp_timeout_time_wait = 15\nnet.ipv4.ip_forward = 1\n\nnet.ipv4.tcp_max_tw_buckets = 131072\nnet.ipv4.tcp_max_orphans = 3276800" >> /etc/sysctl.conf
sysctl -p

# Load nf_conntrack module
modprobe nf_conntrack

# Add nf_conntrack to /etc/modules
echo "nf_conntrack" >> /etc/modules

# Create reboot.sh script
echo -e "#!/bin/bash\n\n/usr/sbin/resolvconf -u\nsystemctl restart resolvconf" > /root/reboot.sh
chmod +x /root/reboot.sh

# Add crontab entry for reboot script
(crontab -l 2>/dev/null; echo "@reboot /bin/bash /root/reboot.sh") | crontab -

echo "Script execution complete."
