#!/bin/sh
#
#
# chkconfig: 2345 09 01
# description: Remove local drive block device nodes

WITHOUT_RC_COMPAT=1
RETVAL=0

# Source function library.
. /etc/init.d/functions

# /.rw -> sda3
dir2dev()
{
	[ -d "$1" ] || return 0
	basename \
		$(readlink -q \
			$(find /sys/dev/block -name "$(mountpoint -d "$1")") \
			2>/dev/null) 2>/dev/null
}

# sda3 -> sda
part2disk()
{
	[ -n "$1" ] || return 0
	cd /sys/block
	if [ -d "$1" ]; then
		echo "$1"
	else
		basename "$(realpath */"$1"/..)" 2>/dev/null
	fi
}

# if /.rw is mounted off a physical block device, save that one
# 0:* (none) isn't present in sysfs, just in case
# real-device /.rw is always a partition
purge_blockdevs()
{
	udevadm settle

	# loop and ram have no device/ but let's spare extra lookups
	find /sys/block \
		! -name "$(part2disk "$(dir2dev /.rw)")" -a \
		! -name "$(part2disk "$(dir2dev /.ro)")"  -a \
		! -name "$(part2disk "$(dir2dev /image)")" -a \
		! -name "loop*" -a \
		! -name "ram*"  -a \
		-type l \
	| while read dev; do
		[ ! -f "$dev/device/delete" ] ||
			echo 1 > "$dev/device/delete"
	done
}

# unrelated strictly but rather relevant
unbrowse_netshares()
{
	GVFS_BIN=/usr/libexec/gvfs/gvfsd-smb-browse
	[ -x "$GVFS_BIN" ] || return 0
	chmod -x "$GVFS_BIN"
}

start()
{
    unbrowse_netshares

    local msg="Removing local drive device nodes"
    echo -n "$msg "

    purge_blockdevs; RETVAL=$?

    [ $RETVAL -eq 0 ] && success "$msg" || failure "$msg"
    echo
    return $RETVAL
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop|condstop|status)
		;;
	restart|reload|condrestart|condreload)
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
