#!/bin/sh
#
# $FreeBSD$
#
# PROVIDE: afsd
# REQUIRE: afsserver named
# KEYWORD: shutdown
#
# We require afsserver for the (rare, untested) case when a client
# and server are running on the same machine -- the client must not
# start until the server is running.
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# afsd_enable (bool):	Set to NO by default.
#			Set it to YES to enable afsd.
#
# Suggested values for a "large" configuration:
# afsd_flags="-stat 2800 -daemons 5 -volumes 128"
#
# Suggested values for a "medium" configuration:
# afsd_flags="-stat 2000 -daemons 3 -volumes 70"
#
# Suggested values for a "small" configuration:
# afsd_flags="-stat 300 -daemons 2 -volumes 50"

. /etc/rc.subr

name="afsd"
rcvar="afsd_enable"

command="%%PREFIX%%/sbin/${name}"
command_args="-dynroot -fakestat-all -afsdb -memcache"

start_precmd="afsd_prestart"
start_postcmd="afsd_poststart"
stop_cmd="afsd_stop"

kmod="libafs"
vicedir="%%PREFIX%%/etc/openafs"
required_modules="libafs:afs"
required_files="${vicedir}/cacheinfo ${vicedir}/ThisCell ${vicedir}/CellServDB"

load_rc_config "$name"

: ${afsd_enable:="NO"}
: ${afsd_flags:="-stat 2800 -daemons 6 -volumes 128"}

afsd_prestart()
{
	local dir

	# need a mountpoint and a cache dir (well, if we have a disk cache)
	# Should use required_dirs, but no good way to extract from cacheinfo
	for dir in $(awk -F: '{print $1, $2}' ${vicedir}/cacheinfo); do
		if [ ! -d "${dir}" ]; then
			err 1 "Directory ${dir} does not exist. Not starting AFS client."
		fi
	done
}

afsd_poststart()
{
	%%PREFIX%%/bin/fs setcrypt -crypt on
}

afsd_stop()
{
	local afsdir

	afsdir=$(awk -F: '{print $1}' ${vicedir}/cacheinfo)
	if ! umount $afsdir; then
		[ -n "${rc_force}" ] && umount -f ${afsdir}
	fi
	kldunload ${kmod}
}

run_rc_command "$1"
