#!/sbin/openrc-run

description="Daemon for ZFS support via FUSE"

DAEMON=/usr/sbin/zfs-fuse
PIDFILE=/var/run/zfs-fuse.pid
NAME=zfs-fuse

ENABLE_ZFS=yes
DAEMON_OPTS=""
RESTART_ON_UPGRADE=no
FORCE_STOP=no

extra_commands="force_stop force_restart"

depend() {
	need localmount
	after modules
	provide zfs-fuse
}

_load_defaults() {
	[ -f /etc/default/zfs-fuse ] && . /etc/default/zfs-fuse
}

upgrade_zpool_cache_location() {
	oldcache=/etc/zfs/zpool.cache
	newcache=/var/lib/zfs/zpool.cache

	if [ -f "$oldcache" ] && [ ! -e "$newcache" ]; then
		ebegin "Moving existing zpool.cache to new location"
		mkdir -p "$(dirname "$newcache")"
		mv "$oldcache" "$newcache"
		eend 0
	elif [ -e "$oldcache" ]; then
		ewarn "old zpool.cache present but no longer used ($oldcache)"
	fi
}

is_running() {
	start-stop-daemon --stop --test --quiet --pidfile "$PIDFILE" \
		--exec "$DAEMON" >/dev/null 2>&1
}

start_pre() {
	[ -x "$DAEMON" ] || return 0
	_load_defaults
	[ "x$ENABLE_ZFS" = "xyes" ] || return 0
	upgrade_zpool_cache_location
	ulimit -v unlimited
	ulimit -c 512000
	ulimit -l unlimited
	ulimit -s unlimited
	unset LANG
	return 0
}

start() {
	start_pre || return $?
	_load_defaults
	[ "x$ENABLE_ZFS" = "xyes" ] || return 0
	if is_running; then
		ewarn "$NAME is already running"
		return 0
	fi
	ebegin "Starting $NAME"
	if [ -n "$DAEMON_OPTS" ]; then
		ewarn "use of DAEMON_OPTS deprecated: use /etc/zfs/zfsrc instead"
	fi
	if start-stop-daemon --start --quiet --pidfile "$PIDFILE" \
		--exec "$DAEMON" -- $DAEMON_OPTS --pidfile "$PIDFILE"; then
		eend 0
	else
		eend 1
		return 1
	fi
	ebegin "Immunizing $NAME against OOM kills and sendsigs signals"
	if [ -f "/proc/$(cat "$PIDFILE")/oom_score_adj" ]; then
		echo -1000 > "/proc/$(cat "$PIDFILE")/oom_score_adj"
		eend 0
	elif [ -f "/proc/$(cat "$PIDFILE")/oom_adj" ]; then
		echo -17 > "/proc/$(cat "$PIDFILE")/oom_adj"
		eend 0
	else
		eend 1
	fi
	ebegin "Mounting ZFS filesystems"
	if zfs mount -a && zfs share -a; then
		eend 0
	else
		eend 1
		return 1
	fi
}

stop() {
	_load_defaults
	if ! is_running; then
		return 0
	fi
	ebegin "Unmounting ZFS filesystems"
	if ! zfs umount -a; then
		eend 1 "possibly due to open files on mounted zfs volumes"
		[ "x$FORCE_STOP" = "xyes" ] || return 1
	else
		eend 0
	fi
	ebegin "Stopping $NAME"
	if start-stop-daemon --stop --quiet --pidfile "$PIDFILE" --exec "$DAEMON"; then
		COUNTER=0
		while is_running; do
			sleep 1
			COUNTER=$((COUNTER + 1))
			if [ "$COUNTER" -ge 12 ]; then
				eend 1 "Timed out"
				return 1
			fi
		done
		rm -f "$PIDFILE"
		eend 0
	else
		eend 1
		return 1
	fi
}

restart() {
	if is_running; then
		ENABLE_ZFS=yes
	fi
	stop && sleep 1 && start
}

force_stop() {
	FORCE_STOP=yes
	stop
}

force_restart() {
	FORCE_STOP=yes
	restart
}

status() {
	status_of_proc -p "$PIDFILE" "$DAEMON" "$NAME"
}
