#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

function error() {
    echo -e "\033[31m$1\033[0m"
}

OS="`getos`"

if ! [ ${UID} = 0 ]; then
    error "This script must be ran as root"
    exit 1
fi

if [ "${OS}" = "Ubuntu" ]; then
    swapfile="/swapfile"
    if ! [ -f "${swapfile}" ]; then
        memmb=`free -m | grep Mem: | awk '{print $2}' \
            | /opt/dosis2/bin/math min 8192 - \
            | /opt/dosis2/bin/math quotient - 2 \
            | /opt/dosis2/bin/math round --floor - --as-type int`
        echo "Creating ${swapfile} of size ${memmb}M"
        dd if=/dev/zero of="${swapfile}" bs=1M count=${memmb}
        chown root.root "${swapfile}"
        chmod 0600 "${swapfile}"
    fi

    swapon --show=NAME | grep -qE "`readlink -f \"${swapfile}\"`$"
    if [ $? != 0 ]; then
        echo "Make swap space in ${swapfile}"
        mkswap -f "${swapfile}"
    fi

    grep -qrE "^${swapfile}\s+" /etc/fstab
    if [ $? != 0 ]; then
        echo "Setup ${swapfile} in /etc/fstab"
        echo "${swapfile} none swap sw 0 0" >> /etc/fstab
    fi
elif [ "${OS}" = "CentOS" ]; then
    swapfile="/dev/mapper/vg_dosis2-lv_swap"

    swapon --summary | grep -qrE "`readlink -f \"${swapfile}\"`\s+"
    if [ $? != 0 ]; then
        echo "Make swap space in ${swapfile}"
        mkswap -f "${swapfile}"
    fi

    grep -qrE "^${swapfile}\s+" /etc/fstab
    if [ $? != 0 ]; then
        echo "Setup ${swapfile} in /etc/fstab"
        echo "${swapfile} swap swap defaults 0 0" >> /etc/fstab
    fi
else
    error "Unsupported OS: ${OS}"
    exit 1
fi

# make sure to enable swap
swapon -a
