#!/sbin/openrc-run
# SPDX-License-Identifier: GPL-2.0-only

depend() {
	need localmount swap
	after bootmisc modules
}

ZramInit() {
	set -- ${1+"$@"} -D "$num_devices" \
		${mlim:+-S "$mlim"} ${back:+-b "$back"} \
		${icmp:+-I} ${idle:+-w} ${wlim:+-W "$wlim"} \
		${maxs:+-s "$maxs"} ${algo:+-a "$algo"} \
		${labl:+-L "$labl"} ${uuid:+-U "$uuid"} ${notr:+-T} \
		${blck:+-B "$blck"} ${irat:+-i "$irat"} ${inod:+-N "$inod"}
	[ -z "${args:++}" ] || eval 'set -- "$@" '"$args"
	if [ x"$fstype" = x'swap' ]
	then	einfo "Swap->zram$2"
		zram-init -p "$flag" ${1+"$@"} -- "$size"
	else	einfo "Mount zram$2 $fstype"
		zram-init -t "$flag" \
			${opts:+-o "$opts"} \
			${owgr:+-c "$owgr"} \
			${mode:+-m "$mode"} \
			${1+"$@"} -- "$size" "$fstype"
	fi
	eend $?
}

ZramStop() {
	if [ x"$fstype" = x'swap' ]
	then	einfo "Remove zram$2 swap"
		zram-init ${1+"$@"} -- 0
	else	einfo "Umount zram$2 $fstype"
		zram-init ${1+"$@"} -- 0 "$fstype"
	fi
	eend $?
}

ZramSanityCheck() {
	num_device=${num_devices#+}
	num_device=${num_devices#0}
	: ${num_devices:=0}
	case $num_devices in
	*[!0-9]*)
		return 1;;
	esac
	[ "$num_devices" -gt 0 ]
}

ZramIgnore() {
	eval "fstype=\${type$1-} opts=\${opts$1-}
		size=\${size$1:-0}
		mlim=\${mlim$1-}
		back=\${back$1-}
		icmp=\${icmp$1-}
		idle=\${idle$1-}
		wlim=\${wlim$1-}
		maxs=\${maxs$1-}
		algo=\${algo$1-}
		flag=\${flag$1-}
		blck=\${blck$1-}
		irat=\${irat$1-}
		inod=\${inod$1-}
		owgr=\${owgr$1-}
		mode=\${mode$1-}
		labl=\${labl$1-}
		uuid=\${uuid$1-}
		notr=\${notr$1-}
		args=\${args$1-}"
	case $fstype in
	'-'|swap|/*)
		! [ "$size" -gt 0 ];;
	esac
}

start() {
	ZramSanityCheck || return 0

	if yesno "$load_on_start"
	then	einfo 'Loading zram module...'
		modprobe zram "num_devices=$num_devices"
		eend $?
	fi

	i=0
	while [ $i -lt "$num_devices" ]
	do	ZramIgnore "$i" || ZramInit -d "$i"
		i=$(( $i + 1 ))
	done
	:
}

stop() {
	ZramSanityCheck || return 0

	i=0
	while [ $i -lt "$num_devices" ]
	do	ZramIgnore "$i" || ZramStop -d "$i"
		i=$(( $i + 1 ))
	done

	if yesno "$unload_on_stop" in
	then	einfo 'Unloading zram module...'
		modprobe -r zram
		eend $?
	fi
}
