#!/usr/bin/env bash
# https://www.kernel.org/doc/Documentation/blockdev/zram.txt

apt install -y insserv
apt install -y zram-tools  # Provides /etc/default/zramswap

CORES=1		# By default, zramswap-start will use all available cores.
PERCENTAGE=10	# Specifies percentage of available RAM that should be used for zram
ALLOCATION=256	# static amount of RAM that should be used, in MiB
PRIORITY=100	# Specifies the priority for the swap devices, see swapon(2)

#sed -i '/^#CORES=.*/ s/.*/&\nCORES=\"\"/' /etc/default/zramswap
sed -i '/^#PERCENTAGE=.*/ s/.*/&\nPERCENTAGE=\"\"/' /etc/default/zramswap
sed -i '/^#ALLOCATION=.*/ s/.*/&\nALLOCATION=\"\"/' /etc/default/zramswap
sed -i '/^#PRIORITY=.*/ s/.*/&\nPRIORITY=\"\"/' /etc/default/zramswap

#sed -i 's,^\(CORES=\).*,\1'\"${CORES}\"',' /etc/default/zramswap
sed -i 's,^\(PERCENTAGE=\).*,\1'\"${PERCENTAGE}\"',' /etc/default/zramswap
sed -i 's,^\(ALLOCATION=\).*,\1'\"${ALLOCATION}\"',' /etc/default/zramswap
sed -i 's,^\(PRIORITY=\).*,\1'\"${PRIORITY}\"',' /etc/default/zramswap

# https://wiki.debian.org/ZRam

cat > /etc/init.d/zram <<'EOF'
#!/bin/sh
### BEGIN INIT INFO
# Provides:          zram
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     S
# Default-Stop:      0 1 6
# Short-Description: Use compressed RAM as in-memory swap
# Description:       Use compressed RAM as in-memory swap
### END INIT INFO

# Author: Antonio Galea <antonio.galea@gmail.com>
# Thanks to Przemysław Tomczyk for suggesting swapoff parallelization
# Distributed under the GPL version 3 or above, see terms at
#      https://gnu.org/licenses/gpl-3.0.txt

FRACTION=75

MEMORY=`perl -ne'/^MemTotal:\s+(\d+)/ && print $1*1024;' < /proc/meminfo`
CPUS=`nproc`
SIZE=$(( MEMORY * FRACTION / 100 / CPUS ))

case "$1" in
  "start")
    param=`modinfo zram|grep num_devices|cut -f2 -d:|tr -d ' '`
    modprobe zram $param=$CPUS
    for n in `seq $CPUS`; do
      i=$((n - 1))
      echo $SIZE > /sys/block/zram$i/disksize
      mkswap /dev/zram$i
      swapon /dev/zram$i -p 10
    done
    ;;
  "stop")
    for n in `seq $CPUS`; do
      i=$((n - 1))
      swapoff /dev/zram$i && echo "disabled disk $n of $CPUS" &
    done
    wait
    sleep .5
    modprobe -r zram
    ;;
  "status")
    swapon -s
    ;;
  *)
    echo "Usage: `basename $0` (start | stop)"
    exit 1
    ;;
esac
EOF

chmod +x /etc/init.d/zram

insserv zram
