#!/bin/bash
#####
# Helper script to enable zram (compressed RAM-based block devices)
#
# Load the kernel module, add zram based SWAP with passed size
# pass the desired size of the SWAP as first argument
#####

if [ $# -ne 1 ]; then
    echo "Usage: $0 <memory_size>"
    echo "Example: $0 256M"
    exit 1
fi
memory_size="$1"

# Check if there is already a swap device using zram
if grep -q "^/dev/zram" /proc/swaps; then
    echo "A zram swap device is already loaded. Exiting..."
    exit 0
fi

# Check if zram module is loaded
if lsmod | grep -q "^zram "; then
    echo "zram module is already loaded."
else
    echo "zram module is not loaded. Loading..."
    modprobe zram num_devices=0
fi

# create a new zram device for SWAP
device_number=$(cat /sys/class/zram-control/hot_add)
echo "Added zram device with device number: $device_number"

echo "$memory_size" > /sys/block/zram$device_number/disksize
mkswap /dev/zram$device_number
swapon /dev/zram$device_number

echo "swap enabled"
