#!/bin/bash

. ${TOOLKIT}-functions.sh


# search for mounted filesystems, ignoring some fs types
#
mounted_fs()
{
	local done_dir=/tmp/done_dir.$$.tmp
	local done_dev=/tmp/done_dev.$$.tmp

	:> $done_dir
	:> $done_dev

	cat /proc/mounts | while read dev dir type parms
	do
		# ignored paths
		case $dir in
		 /dev|/dev/*)	continue ;;
		 /sys|/sys/*)	continue ;;
		 /proc|/proc/*)	continue ;;
		 /run|/run/*)	continue ;;
		esac

		# ignore those types
		case $type in
			tmpfs|rootfs|sysfs|binfmt_misc|devpts|proc) continue ;;
			udev|pstore|rpc_pipefs)	continue ;;
		esac
		grep -q "^$dir$" $done_dir && continue
		grep -q "^$dev$" $done_dev && continue
		[ -d $dir ] && echo $dir	# may not exists, if in chroot jail
		echo $dir >>$done_dir
		echo $dev >>$done_dev
	done

	rm -f $done_dir $done_dev
}


# runlevel check, default is run only in singleuser state
#
runlevel=$(runlevel | cut -d' ' -f2)

[ $runlevel != S ] && {
	# default is abort, can be overriden by config
	#
	getconfirm module-userbase.allow_multiuser || {
	    putwarning "wrong runlevel" "
		It's better to run this module in runlevel 1 (single user)!
		Reboot in single user, umount all unnecessary filesystems,
		and try again, or set 'allow_multiuser' to 'yes' in
		[module-userbase] of your configuration.
	    "
	    exit 1
	}
}

# deve controllare se ci sono filesystem montati?
#
getconfirm module-userbase.ignore_mounts && exit 0

# check: no mounted fs other than builtin allowed or explicit
#	defined allowed
#
mounted_dirs=
allowed_fs=$(jtconf module-userbase.allowed_fs 2>/dev/null | tr '[,]' '[ ]')

# builtin allowed fs:
#  /
#  /dev...
#  /boot
#  /sys/*
#
ok_fs='^/$|^/dev/\.static/dev|^/boot$|^/boot/efi$|^/sys/'

for dir in $(jtconf module-userbase.allowed_fs 2>/dev/null | tr '[,]' '[ ]')
do
	ok_fs="$ok_fs|^${dir}$"
done

mounted_dirs=
can_run=true

for dir in $(mounted_fs)
do
	echo "$dir" | egrep -q "$ok_fs" || {
		can_run=false
		mounted_dirs="$mounted_dirs $dir"
	}
done
$can_run || {
	putwarning "ERROR: spurious mounted partition detected!" "
		This module requires NO disks or partitions
		mounted other than root, detected now:\n\n
		$mounted_dirs\n\n
		Please umount all unnecessary
		partitions and relaunch the job, or define the
		allowed filesystems using the proper variable
		module-userbase.allowed_fs (now: '$allowed_fs')"
	exit 1
}

exit 0
