#!/bin/bash
#
# rc file for automount using a Sun-style "master map".
#
### BEGIN INIT INFO
# Provides:		autofs
# Required-Start:	$local_fs
# Required-Stop:	$local_fs
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	automount daemon
# Description:		daemon to mount (possibly remote) filesystems
#			automatically upon entering the mountpoint
### END INIT INFO

#
# Location of the automount daemon and the init directory
#
DAEMON=/usr/sbin/automount
prog=`basename $DAEMON`
MODULE="autofs4"
confdir=/etc/default

test -e $DAEMON || exit 0

PATH=/sbin:/usr/sbin:/bin:/usr/bin
export PATH

#
# load customized configuation settings
#
if [ -r $confdir/autofs ]; then
	. $confdir/autofs
fi

function start() {
	echo -n "Starting $prog: "

	# Make sure autofs4 module is loaded
	if ! grep -q autofs /proc/filesystems
	then
		# Try load the autofs4 module fail if we can't
		modprobe $MODULE >/dev/null 2>&1
		if [ $? -eq 1 ]
		then
			echo "Error: failed to load autofs4 module."
			return 1
		fi
	elif ([ -f /proc/modules ] && lsmod) | grep -q autofs[^4]
	then
		# wrong autofs filesystem module loaded
		echo
		echo "Error: autofs kernel module is loaded, autofs4 required"
		return 1
	fi

	start-stop-daemon --start --exec $DAEMON --oknodo -- $OPTIONS 
	RETVAL=$?
	if [ $RETVAL -eq 0 ] ; then
		echo "done."
	else
		echo "no valid automount entries defined."
	fi
	return 0
}

function stop() {
	echo -n $"Stopping $prog: "
	count=0
	while [ -n "`pidof $DAEMON`" -a $count -lt 15 ] ; do
		start-stop-daemon --stop --exec $DAEMON --oknodo
		[ -z "`pidof $DAEMON`" ] || sleep 3
		count=`expr $count + 1`
	done
	if [ -z "`pidof $DAEMON`" ] ; then
		RETVAL=0
		echo "done."
	else
		RETVAL=1
		echo "failed."
	fi
	return $RETVAL
}

function restart() {
	stop
	start
}

function reload() {
	pid=`pidof $DAEMON`
	if [ -z $pid ]; then
		echo $"$prog not running"
		RETVAL=1
	else
		kill -HUP $pid 2> /dev/null
		echo $"Reloading maps"
		RETVAL=0
	fi
	return $RETVAL
}

RETVAL=0

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|force-reload)
		restart
		;;
	reload)
		reload
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|reload|force-reload}"
		exit 1;
		;;
esac

exit $?
