#! /bin/sh

set -e


PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/arlad
OPTIONS="-z"
NAME=arlad
DESC="Arla Daemon"

test -f $DAEMON || exit 0
test -c /dev/xfs0 || exit 0

case "$1" in
  start)
        echo -n "Loading Xfs user-space filesystem kernel module..."
	modprobe xfs || (echo "fail" && echo "You need to install arla-modules-source and compile kernel module" && echo "Read  /usr/share/doc/arla-modules-source/README.Debian" && exit 0)
	echo done

	echo -n "Starting $DESC: "
	start-stop-daemon --start --quiet --oknodo --pidfile /var/run/$NAME.pid --name $NAME --exec $DAEMON -- $OPTIONS
	echo "$NAME."
	
	sync ; sleep 1

	if mount -t xfs | grep -q /afs ; then
	   echo "AFS already mounted on /afs"
        else
	   echo -n "Mounting AFS filesystem..."
	   mount -t xfs arla /afs
           echo done
        fi

	;;
  stop)
	echo -n "Stopping $DESC: "
	start-stop-daemon --stop  --quiet --oknodo --pidfile /var/run/$NAME.pid --name $NAME
	echo "$NAME."
	sleep 1

	if mount -t xfs | grep -q /afs ; then
	   echo -n "Unmounting AFS filesystem..."
	   umount /afs
	   echo "Done"
        else
	   echo "AFS not mounted, not unmounting"
        fi

        if lsmod | grep -q ^xfs ; then
	   echo -n "Removing Xfs user-space filesystem kernel module..."
	   rmmod xfs || true
	   echo done
        else
	   echo "Xfs user-space filesystem kernel module not installed not removing."
        fi

	;;
  #reload)
	#
	#	If the daemon can reload its config files on the fly
	#	for example by sending it SIGHUP, do it here.
	#
	#	If the daemon responds to changes in its config file
	#	directly anyway, make this a do-nothing entry.
	#
	#echo "Reloading $DESC configuration files."
	#start-stop-daemon --stop --signal USR1 --quiet --pidfile \
        #	/var/run/$NAME.pid --name $NAME
  #;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	$0 stop
        sleep 3
	$0 start
	;;
  *)
	N=/etc/init.d/$NAME
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
