#!/sbin/runscript
# Copyright 1999-2003 Gentoo Technologies, Inc.
# Distributed under the terms of the GNU General Public License v2
# $Header: /home/cvsroot/gentoo-src/rc-scripts/init.d/netmount,v 1.23 2003/03/09 09:06:23 azarah Exp $


depend() {

	local myneed="net"
	local myuse=""
	
	#
	# Only have Portmap as a dependency if there is a nfs mount in fstab
	# that should be mounted at boot time.  Also filter out comments.
	#
	local nfsmounts="$(awk '!/^#/ && $3 == "nfs" && $4 !~ /noauto/ { print $0 }' /etc/fstab)"
	
	if [ -n "${nfsmounts}" ]
	then
		local myneed="${myneed} portmap"
		local myuse="${myuse} nfs"
	fi

	need ${myneed}
	use ${myuse}
}

start() {
	local rcfilesystems=""

	# Only try to mount NFS filesystems if portmap was started.
	# This is to fix "hang" problems for new users who do not
	# add portmap to the default runlevel.
	if [ -L ${svcdir}/started/portmap ]
	then
		rcfilesystems="coda,nfs,ncpfs,smbfs"
	else
		rcfilesystems="coda,ncpfs,smbfs"
	fi

	ebegin "Mounting network filesystems"
	mount -at ${rcfilesystems} >/dev/null

	if [ "$?" -ne 0 ]
	then
		ewend 1 "Could not mount all network filesystems!"
	else
		eend 0
	fi

	return 0
}

stop() {
	# umount -art $fstypes doesn't seem to work, so...
	# NB: we have to check if any network filesystems is mounted,
	#     else mount do not exit cleanly

	local sig retry
	local remaining="$(awk '$3 ~ /coda|nfs|ncpfs|smbfs/ { if ($2 != "/") print $2 }' /proc/mounts | sort -r)"

	# just keep things nice and uniform
	if [ -z "${remaining}" ]
	then
		ebegin "Unmounting network filesystems"
		eend 0
	else
	        sig=
	        retry=3
	        while [ -n "${remaining}" -a "${retry}" -gt 0 ]
	        do
	                if [ "${retry}" -lt 3 ]
			then
	                        ebegin "Unmounting network filesystems (retry)"
	                        umount ${remaining} &>/dev/null
	                        eend $? "Failed to unmount filesystems this retry"
	                else
	                        ebegin "Unmounting network filesystems"
	                        umount ${remaining} &>/dev/null
	                        eend $? "Failed to unmount filesystems"
	                fi
	                remaining="$(awk '$3 ~ /coda|nfs|ncpfs|smbfs/ { if ($2 != "/") print $2 }' /proc/mounts | sort -r)"
	                [ -z "${remaining}" ] && break
	                /bin/fuser -k -m ${sig} ${remaining} &>/dev/null
	                sleep 5
	                retry=$((${retry} -1))
	                sig=-9
	        done
	fi
}


# vim:ts=4
