#!/bin/bash

# Add/overwrite sysctl configurations
cat <<EOT > /etc/sysctl.conf
net.core.default_qdisc = fq
net.core.rmem_max = 67108848
net.core.wmem_max = 67108848
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.tcp_congestion_control = bbr
net.ipv4.tcp_rmem = 16384 16777216 536870912
net.ipv4.tcp_wmem = 16384 16777216 536870912
net.ipv4.tcp_adv_win_scale = -2
net.ipv4.tcp_sack = 1
net.ipv4.tcp_timestamps = 1
kernel.panic = -1
vm.swappiness = 1
EOT

# Apply sysctl settings
sysctl -p 

# Detect if system has swap, if not create 1G swap file
if [ -z "$(swapon -s)" ]; then
  # Create and configure 1G swap file
  SWAP_FILE=/swapfile

  # Remove existing swap file if exists
  swapoff "$SWAP_FILE" 2>/dev/null
  rm -f "$SWAP_FILE"

  # Create 1G swap file
  dd if=/dev/zero of="$SWAP_FILE" bs=1M count=1024

  # Set proper permissions
  chmod 600 "$SWAP_FILE"

  # Make the swap file
  mkswap "$SWAP_FILE"

  # Enable the swap
  swapon "$SWAP_FILE"

  # Update /etc/fstab to use swap file
  sed -i '/swapfile/d' /etc/fstab
  echo "$SWAP_FILE none swap defaults 0 0" >> /etc/fstab
fi

# Install watchdog
if [ -f /etc/debian_version ]; then
  apt-get update && apt-get install -y watchdog
  systemctl enable watchdog
  systemctl start watchdog
elif [ -f /etc/redhat-release ]; then
  yum install -y watchdog
  systemctl enable watchdog
  systemctl start watchdog
elif [ -f /etc/arch-release ]; then
  pacman -Syu watchdog
  systemctl enable watchdog
  systemctl start watchdog
elif [ -f /etc/gentoo-release ]; then
  emerge --sync
  emerge watchdog
  rc-update add watchdog default
  rc-service watchdog start
elif [ -f /etc/SuSE-release ]; then
  zypper install -y watchdog
  systemctl enable watchdog
  systemctl start watchdog
else
  echo "Unsupported Linux distribution"
  exit 1
fi

