#! /bin/sh

set -e

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/usr/sbin/arlad
OPTIONS="-z -f"

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

case "$1" in
  start)
    # This now seems to need to be manually loaded before arlad is started
    echo -n "Loading Xfs user-space filesystem kernel module..."
    modprobe xfs
    echo done

    echo -n "Starting Arla AFS client daemon:"
    echo -n \ arlad ; start-stop-daemon --oknodo --start --exec $DAEMON -- $OPTIONS
    echo .

    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 Arla AFS client daemon:"
    echo -n \ arlad ; start-stop-daemon --oknodo --stop --exec $DAEMON
    echo .

    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
    ;;
  restart|force-reload)
    echo -n "Stopping Arla AFS client daemon:"
    echo -n \ arlad ; start-stop-daemon --oknodo --stop --exec $DAEMON
    echo .

    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

    sleep 2

    echo -n "Starting Arla AFS client daemon:"
    echo -n \ arlad ; start-stop-daemon --oknodo --start --exec $DAEMON -- $OPTIONS
    echo .

    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
    ;;
  *)
    echo "Usage: /etc/init.d/arla {start|stop|restart|force-reload}"
    exit 1
    ;;
esac

exit 0
