#!/bin/sh

. /etc/init.d/functions

license=""
service=iscsid
execute="/usr/sbin/iscsid"
exeopts=""
trueexe="/usr/sbin/iscsid"
stopexe="killall iscsid"
iscsiconf="/etc/iscsi/initiatorname.iscsi"

SQLITE_DB_PATH="/etc/base/nasdb"

service_status(){
	ps ax | grep $trueexe | grep -v grep > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		echo $service "running"
		exit 1
	else
		echo $service "stopped"
	fi
}

service_prepare(){
	local mountpath=""
        local currtpath=`pwd`
	local scst=`service iscsi-scst status`
	echo "$scst" | grep "running" >/dev/null
	[ $? -ne 0 ] && {
		service iscsi-scst start
		sleep 1
	}
	service_status
	# check db has scsi share folder
	# if not then create
	echo "select * from share where foldername='iscsi';" | sqlite3 $SQLITE_DB_PATH > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		echo "DELETE FROM share WHERE foldername='iscsi';" | sqlite3 $SQLITE_DB_PATH
	fi

	local iName=`awk -F= '{print $2}' $iscsiconf`
	[ -z "$iName" ] && rm -f $iscsiconf
	if [ ! -f $iscsiconf ]; then
		echo "InitiatorName=`/usr/sbin/iscsi-iname`" > $iscsiconf
	fi
}

service_start(){
    	[ ! -d /var/run ] && mkdir -p /var/run

    	service_prepare
	runprocess $service $execute $exeopts # run it to background
	sleep 2
	local pids=`pidof $execute`
	if [ ! -z "$pids" ]; then
		(/etc/tos/scripts/mntother &)
	fi
}

service_stop(){
	stoprocess $service $execute $exeopts
	sleep 2
	(/etc/tos/scripts/mntother &)
}

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
