#!/bin/ksh
#
# Configure the zram(4) disks listed in /etc/zramctl.conf and add their
# b partitions as swap space.

daemon="/usr/local/sbin/zramctl"

. /etc/rc.d/rc.subr

rc_reload=NO

rc_check() {
	swapctl -l 2>/dev/null | grep -q '^/dev/zram'
}

rc_start() {
	local _dev _line _ret=0

	[[ -f /etc/zramctl.conf ]] || return 1
	if (($(sysctl -n kern.securelevel) > 1)); then
		echo "${0##*/}: swap cannot be added at securelevel 2," \
		    "see zramctl.conf(5)" >&2
		return 1
	fi
	while read -r _line; do
		_line=${_line%%#*}
		set -- ${_line}
		(($# > 0)) || continue
		eval _dev=\${$#}
		if ! ${daemon} "$@"; then
			_ret=1
		elif ! swapctl -a /dev/${_dev}b; then
			${daemon} -u ${_dev}
			_ret=1
		fi
	done </etc/zramctl.conf

	# Use zram(4) swap before the other swap devices left at priority 0.
	if rc_check; then
		for _dev in $(swapctl -l |
		    sed -n '/^\/dev\/zram/d;s,^\(/[^ ]*\) .* 0$,\1,p'); do
			swapctl -c -p 1 ${_dev}
		done
	fi
	return ${_ret}
}

rc_stop() {
	local _dev

	for _dev in $(swapctl -l | sed -n 's,^/dev/\(zram[0-9]*\)b .*,\1,p'); do
		swapctl -d /dev/${_dev}b && ${daemon} -u ${_dev}
	done
}

rc_cmd $1
