#!/bin/bash
#
# pstorage-fs         Mount pstorage filesystems.
#
# chkconfig: 345 56 75
# description: Mounts and unmounts all pstorage File System mount points.
### BEGIN INIT INFO
# Provides: $remote_fs
# Short-Description: Mount and unmount pstorage network filesystems.
# Description: Mount and unmount pstorage network filesystems.
### END INIT INFO

[ -f /etc/sysconfig/network ] || exit 0
. /etc/init.d/functions
. /etc/sysconfig/network

PSTORAGEFSTAB=$(LC_ALL=C awk '!/^#/ && $3 ~ /^fuse.pstorage/ && $4 !~ /noauto/ { print $2 }' /etc/fstab)
PSTORAGEMTAB=$(LC_ALL=C awk '$3 ~ /^fuse.pstorage/ && $2 != "/" { print $2 }' /proc/mounts)
PSTORAGE_FS_TYPE="65735546"
PSTORAGE_OUT="/tmp/pstoragefs_out.$$"
TIMEOUT=120

# See how we were called.
case "$1" in
  start)
        /sbin/ip a l | grep global 2>&1 >/dev/null
        [ $? -ne 0 ] && exit 0
        [ "$EUID" != "0" ] && exit 4
        [ ! -n "$PSTORAGEFSTAB" ] && exit 0
        for pstorage_mpoint in $PSTORAGEFSTAB; do
		# Check that it's already mounted
		already_mounted=0
		for pstorage_mounted in $PSTORAGEMTAB; do
			if [ $pstorage_mounted = $pstorage_mpoint ]; then
				already_mounted=1
				break
			fi
		done

		# Mount it
		if [ $already_mounted -eq 0 ]; then
			action $"Mounting pstorage filesystem $pstorage_mpoint: " mount $pstorage_mpoint
			[ $? -ne 0 ] && continue
		fi

		# Wait for pstorage really mounted
		rm -f $PSTORAGE_OUT > /dev/null 2>&1
		fstype=""
		stat -f -c %t $pstorage_mpoint > $PSTORAGE_OUT 2>/dev/null &
		pid="$!"
		while [ $TIMEOUT -ne 0 ]; do
			kill -0 $pid >& /dev/null
			if [ $? -ne 0 ]; then
				# stat exit
				fstype=`cat $PSTORAGE_OUT`
				rm -f $PSTORAGE_OUT > /dev/null 2>&1
				if [ "x$fstype" = "x$PSTORAGE_FS_TYPE" ]; then
					# OK!
					break
				else
					# Try again
					fstype=""
					stat -f -c %t $pstorage_mpoint > $PSTORAGE_OUT 2>/dev/null &
					pid="$!"
				fi
			fi
			TIMEOUT=$((TIMEOUT-1))
			sleep 1
		done

		if [ $TIMEOUT -eq 0 -a "x$fstype" != "x$PSTORAGE_FS_TYPE" ]; then
			echo "Timeout waiting pstorage availability on $pstorage_mpoint expired"
		fi
	done
	touch /var/lock/subsys/pstorage-fs
	;;
  stop)
        [ "$EUID" != "0" ] && exit 4
	[ -n "$PSTORAGEMTAB" ] && action $"Unmounting pstorage filesystems: " umount -a -t fuse.pstorage
	rm -f /var/lock/subsys/pstorage-fs
	;;
  status)
	if [ -f /proc/mounts ] ; then
	        [ -n "$PSTORAGEFSTAB" ] && {
		     echo $"Configured pstorage mountpoints: "
		     for fs in $PSTORAGEFSTAB; do echo $fs ; done
		}
	else
		echo $"/proc filesystem unavailable"
	fi
	[ -r /var/lock/subsys/pstorage-fs ] || exit 3
	;;
  restart)
	$0 stop
	$0 start
	exit $?
	;;
  reload)
        $0 start
	exit $?
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|reload|status}"
	exit 2
esac

exit 0
