#!/bin/sh

. /etc/init.d/functions

service=iscsi-scst
execute="/usr/sbin/iscsi-scstd"
trueexe="iscsi-scstd"
svrport=`cat /etc/iscsi-scstd.conf`
exeopts="-p ${svrport}"
SQLITE_DB_PATH="/etc/base/nasdb"

service_status(){
	local pids=`pidof $trueexe`
	if [ ! -z "$pids" ]; then
		echo $service "running"
	else
		echo $service "stopped"
	fi
}

exec_conf(){
    if [ -f $1 ]; then
        sh $1 2>/dev/null
    else
        echo $1 not set
    fi
}

scst_lun_init(){
	[ ! -d /etc/iscsi-target/ ] && return

	for target in /etc/iscsi-target/*; do
		if [ -f $target/TARGET ]; then
			exec_conf $target/TARGET
		else
			echo $target/TARGET not exists
			continue
		fi

		exec_conf $target/HEADCRC
		exec_conf $target/DATACRC
		exec_conf $target/CHAP

		for lun in $target/LUN*; do
			exec_conf $lun
		done
	done
}

scst_lun_stop(){
	[ ! -d /etc/iscsi-target/ ] && return
	for file in `ls /mnt/md?/iscsi-spare-vdisk? 2>/dev/null`; do
		local key=${file:0-1}
		echo "del_device spare${key}" > /sys/kernel/scst_tgt/handlers/vdisk_fileio/mgmt 2>/dev/null
	done
}

service_start(){
    [ ! -d /var/lib/scst/pr ] && mkdir -p /var/lib/scst/pr

    local pids=`pidof $trueexe`
	[ ! -z "$pids" ] && return 0
	runprocess $service $execute $exeopts
	sleep 1
	# initialize scst lun
    scst_lun_init
	sleep 1
	[ ! -f /sys/kernel/scst_tgt/targets/iscsi/enabled ] && return
	echo 1 > /sys/kernel/scst_tgt/targets/iscsi/enabled
}

service_stop(){
	scst_lun_stop
	stoprocess $service $execute $exeopts
}

service_restart(){
	service_stop
	service_start
}

case $1 in
    start)
        service_start
        exit 0 ;;
    stop)
        service_stop
        exit 0 ;;
    restart)
        service_restart
        exit 0 ;;
    status)
        service_status
        exit 0 ;;
    *)
        echo "Usage: `basename $0` {start|stop|restart|status}"
        exit 1 ;;
esac
