#!/bin/sh
#
# $FreeBSD: sysutils/fusefs-kmod/files/fusefs.in 300897 2012-07-14 14:29:18Z beat $
#
# PROVIDE: fusefs
# REQUIRE: sysctl
# BEFORE: mountlate
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# fusefs_enable (bool):		Set to NO by default.
#				Set it to YES to enable fusefs.
#
# fusefs_safe (bool):		Set to NO by default.
#				Set it to YES to wait for all write operations
#				to finish before terminating.
#
# fusefs_safe_evil (bool):	Set to NO by default.
#				Set it to YES to pause the watchdog timer
#				while waiting for write operations.
#

. /etc/rc.subr

name="fusefs"
rcvar=fusefs_enable

kmod="/usr/local/modules/fuse.ko"

start_cmd="fusefs_start"
stop_cmd="fusefs_stop"

fusefs_start()
{
	if kldstat | grep -q fuse\\.ko; then
		echo "${name} is already running."
		return 0
	fi
	echo "Starting ${name}."
	kldload $kmod
}

fusefs_stop()
{
	if ! kldstat | grep -q fuse\\.ko; then
		echo "${name} is not running."
		return 1
	fi
	echo "Stopping ${name}."
# Unmount FUSE filesystems in reverse order (in case they are nested) to
# allow recent FUSE implementation to synchronize disks before shutdown.
	mount | sed -e '1!G;h;$!d' | while read dev d1 mountpoint d2; do
		case "$dev" in
		/dev/fuse[0-9]*)
			echo "fusefs: unmounting ${mountpoint}."
			umount -f $mountpoint
			;;
		esac
	done
	if checkyesno "${name}_safe_evil"; then
		if [ -n "$_rcshutdown_watchdog" ]; then
			echo "fusefs: pausing watchdog timer."
			kill -STOP "$_rcshutdown_watchdog"
		fi
	fi
	if checkyesno "${name}_safe"; then
		printf "fusefs: unloading $kmod... "
		while ! kldunload $kmod 2> /dev/null; do
			sleep 0.25
		done
		echo "done."
	else
		kldunload $kmod
	fi
	if checkyesno "${name}_safe_evil"; then
		if [ -n "$_rcshutdown_watchdog" ]; then
			echo "fusefs: continuing watchdog timer."
			kill -CONT "$_rcshutdown_watchdog"
		fi
	fi
}
load_rc_config $name

: ${fusefs_enable="NO"}
: ${fusefs_safe="NO"}
: ${fusefs_safe_evil="NO"}

run_rc_command "$1"
