#!/bin/bash
#
# Start the iSCSI Enterprise Target.
#
# chkconfig: - 81 19
# description: Start and stop iSCSI target daemon, load and unload kernel module.
# config:  /etc/ietd.conf

# Source function library.

if [ -f /etc/init.d/functions ] ; then
	. /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
	. /etc/rc.d/init.d/functions
else
	exit 0
fi


PATH=${PATH}:/sbin:/bin:/usr/sbin:/usr/bin
MEM_SIZE=1048576
VOLUME_LIST=/proc/net/iet/volume

RETVAL=0

configure_memsize()
{
    if [ -e /proc/sys/net/core/wmem_max ]; then
        echo ${MEM_SIZE} > /proc/sys/net/core/wmem_max
    fi

    if [ -e /proc/sys/net/core/rmem_max ]; then
        echo ${MEM_SIZE} > /proc/sys/net/core/rmem_max
    fi

    if [ -e /proc/sys/net/core/wmem_default ]; then
        echo ${MEM_SIZE} > /proc/sys/net/core/wmem_default
    fi

    if [ -e /proc/sys/net/core/rmem_default ]; then
        echo ${MEM_SIZE} > /proc/sys/net/core/rmem_default
    fi

    if [ -e /proc/sys/net/ipv4/tcp_mem ]; then
        echo "${MEM_SIZE} ${MEM_SIZE} ${MEM_SIZE}" > /proc/sys/net/ipv4/tcp_mem
    fi

    if [ -e  /proc/sys/net/ipv4/tcp_rmem ]; then
        echo "${MEM_SIZE} ${MEM_SIZE} ${MEM_SIZE}" > /proc/sys/net/ipv4/tcp_rmem
    fi

    if [ -e /proc/sys/net/ipv4/tcp_wmem ]; then
        echo "${MEM_SIZE} ${MEM_SIZE} ${MEM_SIZE}" > /proc/sys/net/ipv4/tcp_wmem
    fi
}

start_server()
{
	Result=0
	KIND="iscsi-target"
	echo -n $"Starting $KIND services: "
	configure_memsize
	modprobe -q crc32c || Result=1
	modprobe iscsi_trgt || Result=1
	/usr/sbin/ietd || Result=1
	if (( $Result == 0 ))
	then
		success
		# Touch the lock file to invoke KNN* kill script.
		touch /var/lock/subsys/iscsi-target || Result=1
	else
		failure
	fi
	echo
	RETVAL=$Result
        return $RETVAL
}

stop_target()
{
	Result=0
	if [ -e ${VOLUME_LIST} ]; then
		tid_list=`grep '^tid:' ${VOLUME_LIST} \
			| sed  -n -e 's/^tid:\([0-9]*\)[[:space:]].*/\1/p' \
			`
		for tid in ${tid_list[*]}
		do
			ietadm --op delete --tid=${tid} || Result=1
		done
	fi
	RETVAL=$Result
	return $RETVAL
}

stop_server()
{
	Result=0
	KIND="iscsi-target"
	echo -n $"Shutting down $KIND services: "
	stop_target || Result=1
	ietadm --op delete || Result=1
	killall ietd || Result=1
	modprobe -r iscsi_trgt || Result=1

	if (( $Result == 0 ))
	then
		success
		rm -f /var/lock/subsys/iscsi-target
	else
		failure
	fi
	echo
	RETVAL=$Result
	return $RETVAL
}

case "$1" in
	start)
		start_server
		;;
	stop)
		stop_server
		;;
	restart)
		stop_server
		start_server
		;;
	*)
		echo "Usage: {start|stop|restart}" >&2
		exit 1
		;;
esac

exit $?
