#!/bin/sh
#
# chkconfig: - 39 35
# description: Starts and stops the iSCSI target
#
# pidfile: /var/run/iscsi-scstd.pid
# config:  /etc/iscsi-scstd.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=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
MEM_SIZE=1048576
SCST_CMD=/usr/local/sbin/scstadmin
SCST_CFG=/etc/scst.conf

# Additional modules to load/unload
ADD_MODULES="scst_vdisk scst"

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
}

RETVAL=0

start()
{
	echo -n "Starting iSCSI target service: "
#	configure_memsize
	modprobe -q crc32c 2>/dev/null
	modprobe -q crc32c-intel 2>/dev/null
	modprobe iscsi-scst
	for module in ${ADD_MODULES}; do
		modprobe ${module}
	done
	daemon /usr/local/sbin/iscsi-scstd
	# -d 0xFFFF
	/usr/local/sbin/scstadmin -config /etc/scst.conf
	RETVAL=$?
	echo
	return $RETVAL
}

stop()
{
	echo -n "Stopping iSCSI target service: "
	killall iscsi-scstd
	rmmod -w iscsi-scst
	RETVAL=$?
	modprobe -r crc32c 2>/dev/null
	for m in ${ADD_MODULES}; do
		if [ -e /sys/module/$m ]; then
			rmmod $m
		fi
	done
	if [ $RETVAL -eq 0 ]; then
		echo_success
	else
		echo_failure
	fi
	echo
	return $RETVAL
}

restart()
{
        stop
        start
}

condrestart()
{
	PID=`pidofproc iscsi-scstd`
	if [ $PID ]; then
        	restart
	fi
}

status()
{
	PID=`pidofproc iscsi-scstd`
	if [ ! $PID ]; then
		echo "iSCSI target stopped"
		exit 1
	else
		echo "iscsi-scstd (pid $PID) is running..."
	fi
}

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

exit $?
