#!/bin/bash

MEM=$( free -ok | awk '/^Mem:/ { print $2 }' )
case "$1" in
	start)
		# round values:
		# SIZE=$(( $MEM / 8 ))
		SIZE=$( free -og|awk '/^Mem:/ { print $2 }' )
		SIZE=$(( $SIZE + 1 ))
		SIZE=$(( $SIZE * 1024 * 1024 ))
		SIZE=$(( $SIZE / 8 ))
	;;
	stop)
		SIZE=-1
	;;
	[0-9]*%)
		P=${1%%%}
		SIZE=$(( $MEM * $P ))
		SIZE=$(( $SIZE / 100 ))
	;;
	[0-9]*)
		SIZE=$1
	;;
	*)
		echo "usage: $0 (start|stop|<num>%|<num>)"
		exit 0
	;;
esac


if [ "$SIZE" = "-1" ]; then
  while read a b; do
    case "$a" in
      /dev/zram*)
	swapoff -v $a &
	;;
      *)
	;;
    esac
  done < /proc/swaps
  wait
  for i in /sys/block/zram*/reset; do
    echo 1 > $i
  done
  usleep 500000
  modprobe -r zram
  exit $?
fi

if grep /dev/zram /proc/swaps > /dev/null 2>&1 ; then
  echo zram swap is already active. exit.
  exit
fi

modprobe zram num_devices=2
for i in 0 1; do
  usleep 500000
  echo $SIZE > /sys/block/zram$i/disksize
  mkswap /dev/zram$i
  swapon -p 42 /dev/zram$i
done

cat /proc/swaps

