#!/bin/bash
#
# Copyright (C) 2014  Red Hat, Inc.
#
# Heavily inspired by zramswapon script found in the Simone Sclavi's repository
# at http://software.opensuse.org/package/systemd-zram-service
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.  You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.

set -x

MAX_RAM_ON=2097152

# get the amount of memory in the machine
mem_total_kb=$(grep MemTotal /proc/meminfo | grep -E --only-matching '[[:digit:]]+')

grep -E 'inst\.zram=(on|1)' /proc/cmdline > /dev/null
force=$?
if [ \( $mem_total_kb -gt $MAX_RAM_ON \) -a \( $force != "0" \) ]; then
    # more than 1 GB of RAM and not forced, do nothing
    exit 0
fi

# get the number of CPUs
num_cpus=$(getconf _NPROCESSORS_ONLN)

# load dependency modules
modprobe zram

# set number of streams
echo $num_cpus > /sys/block/zram0/max_comp_streams

# initialize the devices
echo "${mem_total_kb}K" > /sys/block/zram0/disksize

# create and activate swap
mkswap /dev/zram0
swapon -p 100 /dev/zram0

if [ $mem_total_kb -le "1048576" ]; then
    # less than 1 GB or RAM -> less than 512 MB /tmp (tmpfs defaults to
    # 0.5*RAM), bump up the /tmp's size, dnf may need it
    mount -o remount,size=512M /tmp
fi

exit 0
