#! /bin/sh
#
#       Based on a example file to build /etc/init.d/ scripts,
#		written by Miquel van Smoorenburg <miquels@cistron.nl>
#		and later modified by Ian Murdock <imurdock@gnu.ai.mit.edu>.
#
#       Also based on init script mountnfs.sh from initscripts package.
#
#       Modified for aoetools by David Martnez Moreno <ender@debian.org>.
#
### BEGIN INIT INFO
# Provides:          mountaoe
# Required-Start:    $local_fs $network
# Required-Stop:     $local_fs $network
# Should-Start:      
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: Begin AoE discovery and mount related filesystems.
# Description:       Begin AoE discovery and mount filesystems residing.
#                    on AoE volumes.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=aoetools
DESC="AoE devices discovery and mounting AoE filesystems"

[ -f /etc/default/rcS ] && . /etc/default/rcS
. /lib/lsb/init-functions

# Include aoetools defaults if available
if [ -f /etc/default/aoetools ] ; then
	. /etc/default/aoetools
fi

set -e

do_start() {
    modprobe aoe >/dev/null 2>&1 || true

    # We exit if the user do not want us to try this.
    if [ "$INTERFACES" = "none" ]
    then
        echo "not started."
        exit 0
    fi

    if [ ! -c /dev/etherd/discover ]
    then
        echo "Missing devices under /dev/etherd/.  Please run" >&2
        echo "  aoe-mkdevs /dev/etherd" >&2
        echo "and try again."
        exit 1
    fi

    # Try to set up interfaces for discovery, if any.
    if [ ! -z "$INTERFACES" ]
    then
        aoe-interfaces $INTERFACES
    fi

    aoe-discover

    [ -f /etc/fstab ] || return
    #
    # Read through fstab line by line. If it contains /dev/etherd, set the flag
    # for mounting file systems over AoE. 
    #

    exec 9<&0 </etc/fstab

    waitaoe=
    while read DEV MTPT FSTYPE OPTS REST
    do
        case "$OPTS" in
          noauto|*,noauto|noauto,*|*,noauto,*)
            continue
            ;;
        esac
        case "$DEV" in
          ""|\#*)
            continue
            ;;
          /dev/etherd/*)
            waitaoe="$waitaoe $MTPT"
        esac
    done

    exec 0<&9 9<&-

    if [ ! -z "$waitaoe" ]
    then
        echo
    fi

    for mountpt in $waitaoe; do
        echo "Mounting $mountpt..."
        mount $mountpt
        #log_action_begin_msg "Waiting for $mountpt"
    done
}

case "$1" in
  start|restart|reload|force-reload)
	echo -n "Starting $DESC: "

    do_start
    
	#echo "$NAME."
	;;
  stop)
	#echo -n "Stopping $DESC: "
	#echo "$NAME."
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	exit 1
	;;
esac

exit 0
