#!/usr/sbin/openrc-run

description="Unmount remote and non-toplevel virtual filesystems"

depend()
{
	# OpenRC: "after X" => stop before X. Unmount NFS while daemons/net still up,
	# then let sendsigs kill remaining processes.
	after sendsigs networking
	provide umountnfs
}

stop()
{
	local KERNEL RELEASE FLAGS DIRS DEV MTPT FSTYPE OPTS REST ES

	. /lib/init/vars.sh

	KERNEL="$(uname -s)"
	RELEASE="$(uname -r)"

	case "${KERNEL}:${RELEASE}" in
	  Linux:[01].*|Linux:2.[01].*)
		FLAGS=""
		;;
	  Linux:2.[23].*|Linux:2.4.?|Linux:2.4.?-*|Linux:2.4.10|Linux:2.4.10-*)
		FLAGS="-f"
		;;
	  *)
		FLAGS="-f -l"
		;;
	esac

	halt -w

	rm -f /tmp/.clean /run/.clean /run/lock/.clean

	DIRS=""
	while read -r DEV MTPT FSTYPE OPTS REST
	do
		case "$MTPT" in
		  /|/proc|/dev|/dev/pts|/dev/shm|/proc/*|/sys|/run|/run/*)
			continue
			;;
		esac
		case "$FSTYPE" in
		  nfs|nfs4|smbfs|ncp|ncpfs|cifs|coda|ceph)
			DIRS="$MTPT $DIRS"
			;;
		  proc|procfs|linprocfs|devpts|usbfs|usbdevfs|sysfs)
			DIRS="$MTPT $DIRS"
			;;
		esac
		case "$OPTS" in
		  _netdev|*,_netdev|_netdev,*|*,_netdev,*)
			case "$FSTYPE" in
			  ocfs2|gfs)
				;;
			  *)
				DIRS="$MTPT $DIRS"
				;;
			esac
			;;
		esac
	done < /etc/mtab

	if [ "$DIRS" ]
	then
		if [ "$VERBOSE" = no ]
		then
			ebegin "Unmounting remote and non-toplevel virtual filesystems"
			fstab-decode umount $FLAGS $DIRS
			eend $?
		else
			ebegin "Unmounting remote and non-toplevel virtual filesystems"
			fstab-decode umount -v $FLAGS $DIRS
			eend $?
		fi
	fi

	if [ -x /sbin/initctl ]; then
		initctl --quiet emit unmounted-remote-filesystems 2>/dev/null || true
	fi
}

start()
{
	:
}
