#! /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

# ugly hack to create the device if running udev
# Should be removed when arla supports sysfs
if [ -e /dev/.udev.tdb -a ! -c /dev/nnpfs0 ]; then
    mknod /dev/nnpfs0 c 103 0       
fi

if [ ! -e /dev/.devfsd -a ! -c /dev/nnpfs0 ] ; then
    echo "The device /dev/nnpfs0 is not present"
    exit 0
fi


case "$1" in
  start)
        echo -n "Loading nnpfs user-space filesystem kernel module..."
	ERROR=`modprobe nnpfs 2>&1`
	if [ -z "$ERROR" ]; then
	    echo "done"
	else 
	    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
	fi

	if [ ! -c /dev/nnpfs0 ] ; then
	    echo "The device /dev/nnpfs0 is not present"
	    exit 1
	fi

	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 nnpfs | grep -q /afs ; then
	   echo "AFS already mounted on /afs"
        else
	   echo -n "Mounting AFS filesystem..."
	   mount -t nnpfs 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 nnpfs | 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 ^nnpfs ; then
	   echo -n "Removing nnpfs user-space filesystem kernel module..."
	   rmmod nnpfs || true
	   echo done
        else
	   echo "nnpfs 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
