#! /bin/bash
#
#       $Id: rc.autofs,v 1.1 1998/05/25 09:20:55 florian Exp florian $
#
#	rc file for automount using a Sun-style "master map".
#	We first look for a local /etc/auto.master, then a YP
#	map with that name
#

#
# 	We can add local options here
#	e.g. localoptions='rsize=8192,wsize=8192'
#
localoptions=''

#
#	This function will build a list of automount commands to execute in
#	order #	to activate all the mount points. It is used to figure out
#	the difference of automount points in case of a reload
#
function getmounts()
{
#
#	Check for local maps to be loaded
#
if [ -f /etc/auto.master ]
then
    sed -e '/^#/d' -e '/^$/d' /etc/auto.master | (
	while read dir map options
	do
	    if [ ! -z "$dir" -a ! -z "$map" \
			-a x`echo "$map" | cut -c1` != 'x-' ]
	    then
		map=`echo "/etc/$map" | sed -e 's:^/etc//:/:'`
		options=`echo "$options" | sed -e 's/\(^\|[ \t]\)-/\1/g'`
		if [ -x $map ]; then
		    echo "automount $dir program $map $options $localoptions"
		elif [ -f $map ]; then
		    echo "automount $dir file $map $options $localoptions"
		else
		    echo "automount $dir `basename $map` $options $localoptions"
		fi
	    fi
	done
    )
fi

#
#	Check for YellowPage maps to be loaded
#
if [ -e /usr/bin/ypcat ] && [ `ypcat -k auto.master 2>/dev/null | wc -l` -gt 0 ]
then
    ypcat -k auto.master | (
	while read dir map options
	do
	    if [ ! -z "$dir" -a ! -z "$map" \
			-a x`echo "$map" | cut -c1` != 'x-' ]
	    then
		map=`echo "$map" | sed -e 's/^auto_/auto./'`
		options=`echo "$options" | sed -e 's/\(^\|[ \t]\)-/\1/g'`
		echo "automount $dir yp $map $options $localoptions"
	    fi
	done
    )
fi
}

#
#	Status lister.
#
function status()
{
	echo "Configured Mount Points:"
	echo "------------------------"
	getmounts
	echo ""
	echo "Active Mount Points:"
	echo "--------------------"
	ps ax|grep "[0-9]:[0-9][0-9] automount " | (
		while read pid tt stat time command; do echo $command; done
	)
}

case "$1" in
  start)
	getmounts | sh
	;;
  stop)
	killall -TERM automount
	;;
  reload|restart)
	echo "Checking for changes to /etc/auto.master ...."
	TMP1=`tempfile`;
	TMP2=`tempfile`;
	getmounts >$TMP1
	ps ax|grep "[0-9]:[0-9][0-9] automount " | (
	    while read pid tt stat time command; do
		echo "$command" >>$TMP2
		if ! grep -q "^$command" $TMP2; then
			kill -USR2 $pid
			echo "Stop $command"
		fi
	    done
	)
	cat $TMP1 | ( while read x; do
		if ! grep -q "^$x" $TMP2; then
			$x
			echo "Start $x"
		fi
        done )
	rm $TMP1 $TMP2
	;;
  status)
	status
	;;
  *)
	echo "Usage: /etc/init.d/autofs {start|stop|restart|reload|status}"
	exit 1
esac

exit 0
