#!/bin/bash
#
# Start the iSCSI-SCST Target.
#

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
}

start_server()
{
#	configure_memsize

	modprobe -q crc32c 2>/dev/null
	modprobe -q crc32c-intel 2>/dev/null
	modprobe iscsi-scst || { exit $? ; }
	for module in ${ADD_MODULES}; do
		modprobe ${module} || { exit 1 ; }
	done

	/usr/local/sbin/iscsi-scstd

	$SCST_CMD -config $SCST_CFG || { exit $? ; }
}

stop_server()
{
	killall iscsi-scstd
	rmmod -w iscsi-scst || { exit $? ; }
	rmmod ${ADD_MODULES} || { exit $? ; }
}

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

exit $?
