#!/bin/sh
#Copyright: 2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: oneshot; invoke with: sv once umountnfs.sh

exec 2>&1

ebegin() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
eend() { r=${1:-0}; shift || true; [ "$r" -eq 0 ] || [ "${VERBOSE:-}" = no ] || echo "$*" >&2; return "$r"; }
einfo() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
ewarn() { echo "$@" >&2; }
eerror() { echo "$@" >&2; }

. /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
	ebegin "Unmounting remote and non-toplevel virtual filesystems"
	if [ "$VERBOSE" = no ]; then
		fstab-decode umount $FLAGS $DIRS
	else
		fstab-decode umount -v $FLAGS $DIRS
	fi
	eend $?
fi

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