#!/sbin/openrc-run
# Copyright 1999-2018 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

start() {
	ebegin "Starting pentoo-zram"
	RETVAL=0
	if [ -z "${ZRAM_ABSOLUTE}" ]; then
		#echo $(expr $(awk '/MemTotal/ {print $2}' /proc/meminfo) / 3)k
		ZRAM_ABSOLUTE=$(echo "$(awk '/MemTotal/ {print $2}' /proc/meminfo) * 0.${ZRAM_PERCENT:-17}" | bc)k
	fi
	modprobe zram
	sleep 1
	echo $(nproc) >/sys/devices/virtual/block/zram0/max_comp_streams || REVAL=$?
	echo lz4 >/sys/devices/virtual/block/zram0/comp_algorithm || RETVAL=$?
	echo "${ZRAM_ABSOLUTE/\.??/}" > /sys/devices/virtual/block/zram0/disksize || RETVAL=$?
  eindent
  ebegin "Formatting swap"
	timeout -k 31 30 mkswap /dev/zram0 > /dev/null || RETVAL=$?
  if [ "${RETVAL}" = "124" ]; then
    cmdline="$(cat /proc/cmdline)"
    if [ "${cmdline#*cdroot}" != "${cmdline}" ]; then
      eend 124 "mkswap timed out, if you see this a lot \"rc-service del pentoo-zram\""
    else
      eend ${RETVAL} "mkswap timed out, no ZRAM available"
    fi
  else
    eend ${RETVAL}
  fi
  eoutdent
  if [ "${RETVAL}" = "0" ]; then
    ebegin "Activating ZRAM swap device"
	  swapon /dev/zram0 -p 10 > /dev/null || RETVAL=$?
	  eend ${RETVAL}
  fi
}

# Swap gets torn down without help from this init script
#stop() {
#	ebegin "Stopping pentoo-zram"
#	true
#	eend $?
#}
