#!/bin/bash
#set -x
# default factor of 1/2 of RAM
factor=3
# default priority is maximum priority
priority=32767
[ -f /etc/zram.conf ] && source /etc/zram.conf || true
[ -z "$FACTOR" ] || factor=$FACTOR
[ -z "$PRIORITY" ] || priority=$PRIORITY

mem_total=$(free -w | grep "^Mem" | awk '{printf("%d", $2)}') #'
cpu_count=$(getconf _NPROCESSORS_ONLN)

zram_size=$((${mem_total} / ${factor} / 1024))
zram_dev_size=$((${mem_total} / ${factor} / ${cpu_count} / 1024))

# CentOS 7 has old zram module without lz4 and multithreading...
modprobe -q zram num_devices=$cpu_count

for ((i=0; i<$cpu_count; i++)); do
    zramdev=$(zramctl --find --size ${zram_dev_size}MB 2>&1)
    if [ $? -eq 0 ]; then
	mkswap $zramdev >/dev/null
	swapon -p $priority $zramdev
    else
	exit 1
    fi
done

echo -e "\nActivated ZRAM swap device of ${zram_size} MB\n"
