#!/usr/bin/openrc-run

description="Bind mounts single dirs and trees"

. /opt/etc/functions.openrc

depend()
{
	after localmount zfs
	before nfs smbd gluster tftpd libvirtd
	provide ${SVCNAME}
}

do_job() {
	local _bd _bindtab _src _dst _cmd=$1 _order=$2 _rv=0
	if [ "${_order}" = "backward" ]; then
		_bindtab=""
		for _bd in ${BINDTAB}; do
			_bindtab="${_bd} ${_bindtab}"
		done
	else
		_bindtab=${BINDTAB}
	fi
	for _bd in ${_bindtab}; do
		_bd=$(echo ${_bd} | tr ',' ' ')
		case $(echo ${_bd} | awk '{print $1;}') in
			"dir")
				${_cmd} \
					$(echo ${_bd} | awk '{print $2;}') \
					$(echo ${_bd} | awk '{print $3;}') || _rv=1
				;;
			"tree")
				bind_process_tree \
					$(echo ${_bd} | awk '{print $2;}') \
					$(echo ${_bd} | awk '{print $3;}') ${_cmd} || _rv=1
				;;
			*)
				update_me
				eerror "${ME}: malfomed \$BINDTAB: \"${_bd}\""
				_rv=1
				;;
		esac
	done
	return ${_rv}
}

start()
{
	ebegin "Starting \"${SVCNAME}\""
	do_job do_mount_bind forward
	eend $? "Some filesystem(s) still not mounted"
	return 0
}

stop()
{
	ebegin "Stopping \"${SVCNAME}\""
	do_job do_mount_unbind backward
	eend $? "Some filesystem(s) are still in use"
	return 0
}
