#!/sbin/runscript
# Copyright 1999-2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

depend() {
	need net
	after openafs-server
	use logger dns
}

choose_afsdoptions() {
	CACHESIZE=$(cut -d ':' -f 3 /etc/openafs/cacheinfo)
	if [ -z "$OPTIONS" ] || [ "$OPTIONS" = "AUTOMATIC" ] ; then
		if [ $CACHESIZE -lt 131072 ] ; then
			OPTIONS=$SMALL
		elif [ $CACHESIZE -lt 524288 ] ; then
			OPTIONS=$MEDIUM
		elif [ $CACHESIZE -lt 1048576 ] ; then
			OPTIONS=$LARGE
		elif [ $CACHESIZE -lt 2097152 ] ; then
			OPTIONS=$XLARGE
		else
			OPTIONS=$XXLARGE
		fi
	fi
	AFSD_OPTIONS="$OPTIONS $VERBOSE"
	[ "$ENABLE_AFSDB" = "yes" ] && AFSD_OPTIONS="$AFSD_OPTIONS -afsdb"
	[ "$ENABLE_DYNROOT" = "yes" ] && AFSD_OPTIONS="$AFSD_OPTIONS -dynroot"
}

start() {
	local ret=1
	ebegin "Starting OpenAFS client"

	eindent

	# Check if afsd is already running -> abort
	if pgrep -u 0 afsd >/dev/null ; then
		eerror "afsd already running, not attempting to restart"

	# Check if the openafs kernel module is loaded -> attempt unload
	elif [ -d /proc/fs/openafs ] ; then
		ewarn "OpenAFS already active, trying to unload module"
		if ! modprobe -r libafs ; then
			eerror "OpenAFS kernel module was loaded, unloading failed"
		else
			cleanstart
			ret=$?
		fi

	# Everything should be ok, start cleanly
	else
		cleanstart
		ret=$?
	fi

	eend ${ret}
		
	eoutdent

	return ${ret}
}

cleanstart()
{
	# Make sure the mountpoint exists
	mkdir /afs 2> /dev/null

	# Start openafs: module and daemon
	ebegin "Loading OpenAFS kernel module"
	modprobe libafs
	eend $? || return 1

	ebegin "Starting OpenAFS daemon"
	choose_afsdoptions
	/usr/sbin/afsd ${AFSD_OPTIONS} >/dev/null
	eend $?
}

stop() {
	local ret=1
	ebegin "Stopping OpenAFS client"

	eindent

	# Three stage process: unmount / stop daemon / unload module
	ebegin "Unmounting /afs"
	umount /afs
	if eend $? ; then

		ebegin "Stopping OpenAFS daemon"
		/usr/sbin/afsd -shutdown 2>/dev/null
		if eend $? ; then
		
			ebegin "Unloading OpenAFS module"
			modprobe -r libafs
			eend $? && ret=0
		fi
	fi

	eoutdent

	# Clean up: remove the mountpoint if it's an empty directory
	rmdir /afs 2>/dev/null

	return ${ret}
}
