#!/bin/sh
#
# 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.
#
# PROVIDE: afsd
# REQUIRE: afsserver named
# BEFORE: LOGIN
# KEYWORD: shutdown
# 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 doormand.
#

. /etc/rc.subr

name="afsd"
rcvar="afsd_enable"

start_precmd="afsd_prestart"
stop_cmd="afsd_stop"
command="/usr/local/sbin/${name}"

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

load_rc_config "$name"

: ${afsd_enable="NO"}

afsd_prestart()
{
	# 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
			echo "Directory ${dir} does not exist. Not starting AFS client."
			return 2
		fi
	done
	# set up some default args if none given
	afsd_args=${afsd_args:-'MEDIUM'}
	case ${afsd_args} in
	LARGE)
		afsd_args="-stat 2800 -dcache 2400 -daemons 5 -volumes 128"
		;;
	MEDIUM)
		afsd_args="-stat 2000 -dcache 800 -daemons 3 -volumes 70"
		;;
	SMALL)
		afsd_args="-stat 300 -dcache 100 -daemons 2 -volumes 50"
		;;
	esac
	# you probably don't want to change these
	afsd_args="-dynroot -fakestat-all -afsdb -memcache ${afsd_args}"
}

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

run_rc_command "$1"
