#!/bin/bash
#
# /etc/rc.d/init.d/sc101-nbd
#
# Alfredo Barrainkua 2010-03-18 alfredobz@iurreta-institutua.net
# Based in sc101-nbd.init script made by Darrin Khan darrink@gmail.com 
#
# Description: Attach/Detach SC101 mount points
#

# Source function library.
. /lib/lsb/init-functions

UT="/sbin/ut"
SC101CFG="/etc/sc101-nbd.conf"
LOCKFILE="/var/lock/sc101"

# Check to make sure we have the needed files
[ -f ${UT} ] || exit 0
[ -f ${SC101CFG} ] || exit 0

retval=0

start() {
	echo $"Starting SC101-nbd: "
	modprobe nbd
	let retval+=$?
	# for each line in the config, attach the device to the SC101
	for line in `grep -v '^#' $SC101CFG | \
	awk '{ if ($1 ~ /^[a-zA-Z0-9]+$/ && $2 ~ /^\/[a-zA-Z0-9]+\//) print $1","$2 }'`
	do
	   N=`echo $line | cut -f 1 -d ','`
	   P=`echo $line | cut -f 2 -d ','`
	   SCID=`${UT} listall | grep -E "^[0-9a-zA-Z-]{36}\W+$N\W+" | awk '{print $1}'`
	   ps ax | grep "$SCID" | grep attach 1>&2>/dev/null
	   if [ "$?" -eq 0 ] ; then
	      echo "$N already attached!"
	      let retval+=1
           else
	      ${UT} attach ${SCID} $P
	      let retval+=$?
              echo -n '.'
	      mount $P
           fi
	done
	[ "$retval" -eq 0 ] && touch $LOCKFILE
	[ "$retval" -eq 0 ] && log_action_begin_msg $"Starting SC101-nbd: " || log_action_begin_msg $"Starting SC101-nbd: "
	echo  
	return $retval
}	

stop() {
	echo $"Shutting down SC101-nbd: "
	for i in `ps ax | grep "ut " | grep "attach" | awk '{print $1","$8}'`
	do
	    PS=`echo $i | cut -f 1 -d ','`
	    DEV=`echo $i | cut -f 2 -d ','`

#	    echo $PS $DEV
	    umount $DEV
	   kill -TERM $PS
	   let retval+=$?
	done
	[ "$retval" -eq 0 ] && rm -f $LOCKFILE
	[ "$retval" -eq 0 ] && log_action_begin_msg $"Shutting down SC101-nbd: " || log_action_begin_msg $"Shutting down SC101-nbd: "
	echo
	return $retval
}

case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    restart)
    	stop
	start
	;;
    *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
	;;
esac
exit $?
