#! /bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
DAEMON=/usr/sbin/cfsd
NAME=cfsd
DESC=cfs

CONFIG_FILE=/etc/cfs.conf

test -f $DAEMON || exit 0

# source config file
if test -r $CONFIG_FILE; then . $CONFIG_FILE; fi

test -n "$CRYPT_ROOT" || exit 0
test -n "$NULL_EXPORT" || exit 0

missing_export () {
    cat <<EOT >&2
failed.
When using cfs with the nfs-user-server package, add the following line
to /etc/exports and reload the nfs-user-server, then start cfsd again:

$NULL_EXPORT localhost(rw)

Not starting cfs.

EOT
}

set -e

case "$1" in
  start)
	echo -n "Starting $DESC: "
	if test -x /usr/sbin/exportfs; then
	    # nfs-kernel-server
	    exportfs -i -orw localhost:$NULL_EXPORT
	    if ! grep '^/' /etc/exports >/dev/null; then
		# no exports, start temporary rcp.mountd
		rpc.mountd -F --no-nfs-version 3 2>/dev/null &
		MOUNTD=$!
		trap "kill -TERM $MOUNTD" EXIT
		echo -n 'mountd... '
	    fi
	else
	    # nfs-user-server
	    if ! grep "^$NULL_EXPORT[[:space:]]*localhost(rw" \
	      /etc/exports >/dev/null; then
		missing_export
		exit 0
	    fi
	fi
	# start daemon
	env NODAEMON=1 \
	  start-stop-daemon --start --pidfile /var/run/cfs.pid \
	    --make-pidfile --background --exec $DAEMON
	mount -oport=3049,intr,nfsvers=2 \
	    localhost:$NULL_EXPORT $CRYPT_ROOT
	if test -x /usr/sbin/exportfs; then
	    exportfs -u localhost:$NULL_EXPORT
	fi
	echo "$NAME."
	;;
  stop)
	echo -n "Stopping $DESC: "
	start-stop-daemon --oknodo --stop --pidfile /var/run/cfs.pid \
	  && rm -f /var/run/cfs.pid
	umount $CRYPT_ROOT >/dev/null 2>&1 || true
	echo "$NAME."
	;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	echo "Restarting $DESC: "
	$0 stop
	sleep 1
	$0 start
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
