#!/bin/bash

# MUST be run as root
if [ "$(whoami)" != "root" ]; then
    echo "This script MUST be run as root. Goodbye!"
    exit 1
fi

# older convention putting swapfile on app volume, better for GP2 EBS volumes where IOPS are tied to size
#swap_file="/mnt/Sites/swapfile"
# newer convetion putting swapfile on root volume, better for GP3 where base iops is 3k; leaves IOPS on app vol for application
swap_file="/swapfile"

swap_size='1G'
swappiness=10

fallocate -l "$swap_size" "$swap_file"
chmod 600 "$swap_file"
mkswap "$swap_file"
swapon "$swap_file"
sysctl "vm.swappiness=${swappiness}"

#make sure swap is in '/etc/fstab' to presist through reboots
if grep -iq "$swap_file" /etc/fstab; then
    echo "Detected /etc/fstab alread contains '${swap_file}'"
else
    echo "Adding '${swap_file}' /etc/fstab"
    echo  "${swap_file}  none    swap    sw    0   0">>/etc/fstab
fi


#make swappiness persist through reboots by editing '/etc/sysctl.conf' with below
if grep -iq "vm.swappiness=${swappiness}" /etc/sysctl.conf; then
    echo "Detected /etc/sysctl.conf alread contains 'vm.swappiness=${swappiness}'"
else
    echo "Adding 'vm.swappiness=${swappiness}' /etc/sysctl.conf"
    echo  "vm.swappiness=${swappiness}">>/etc/sysctl.conf
fi
